Data Types in JavaScript
JavaScript has two main types of data:
1. Primitive Data Types (immutable, stored directly in memory).
2. Non-Primitive Data Types (reference types, stored in memory by
reference).
1 Primitive Data Types
Data Type Example Description
String "Hello, World!" Text values enclosed in quotes.
Includes integers and floating-point
Number 42, 3.14
numbers.
Boolean true, false Logical values (Yes/No, On/Off).
Null null Represents an intentional absence of value.
A variable declared but not assigned a
Undefined undefined
value.
BigInt 9007199254740991n For large numbers beyond Number limits.
Unique identifiers used for object
Symbol Symbol('id')
properties.
Example:
let message = "Hello, World!"; // String
let count = 42; // Number
let isActive = true; // Boolean
let value = null; // Null
let data; // Undefined (no value assigned)
let bigNumber = 12345678901234567890n; // BigInt
let uniqueID = Symbol("id"); // Symbol
2 Non-Primitive (Reference) Data Types
Data Type Example Description
Key-value pairs for structured
Object { name: "Rahul", age: 25 }
data.
Array [1, 2, 3, 4] Ordered list of values.
function add(a, b) { return a +
Function A reusable block of code.
b; }
Example:
let person = { name: "Rahul", age: 25 }; // Object
let numbers = [1, 2, 3, 4, 5]; // Array
function greet() { console.log("Hello!"); } // Function
3. Type Checking in JavaScript
The typeof operator helps identify data types.
Example:
console.log(typeof "Hello"); // Output: string
console.log(typeof 42); // Output: number
console.log(typeof true); // Output: boolean
console.log(typeof null); // Output: object (Special case)
console.log(typeof undefined); // Output: undefined
console.log(typeof [1, 2, 3]); // Output: object (Arrays are objects)
console.log(typeof function(){}); // Output: function
4. Type Conversion (Casting)
JavaScript automatically converts data types in some cases (type coercion). We
can also manually convert types.
4.1 Implicit Type Conversion (Type Coercion)
JavaScript sometimes converts types automatically.
example
console.log("5" + 5); // Output: "55" (Number converted to String)
console.log("5" - 2); // Output: 3 (String converted to Number)
4.2 Explicit Type Conversion
Use built-in functions like Number(), String(), Boolean().
Example:
let str = "42";
let num = Number(str); // Converts string to number
console.log(num + 5); // Output: 47
let numToString = String(100);
console.log(numToString + " is now a string!"); // Output: 100 is now a string!
let truthy = Boolean(1); // Converts 1 to true
console.log(truthy); // Output: true
note:
Use let and const instead of var.
JavaScript has 7 primitive data types and 3 non-primitive data types.
Use typeof to check data types.
JavaScript allows automatic (implicit) and manual (explicit) type conversion.