JavaScript Data Types
JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type. You can assign a number to a variable and later assign a string to the same variable.
There are 8 basic data types in JavaScript, divided into Primitives and Reference Types.
1. Primitive Types
Primitives are immutable (cannot be changed) and stored directly by value in the stack.
- String: Represents textual data.
let name = "Alice"; - Number: Represents both integers and floating-point numbers.
let n = 123; let f = 12.345; - BigInt: For integers larger than
2^53 - 1.let big = 9007199254740991n; - Boolean: Logical
trueorfalse.let isActive = true; - Undefined: A variable that has not been assigned a value.
let x; // undefined - Null: Represents an intentional absence of any object value.
let y = null; - Symbol (ES6): A unique and immutable identifier, often used for object property keys.
let sym = Symbol("id");
2. Reference Types (Objects)
Reference types are mutable and stored in the heap, with a reference (pointer) stored in the stack.
- Object: A collection of key-value pairs.
- Array: An ordered list of values (technically a special type of object).
- Function: A callable object.
3. The typeof Operator
The typeof operator returns a string indicating the type of the operand.
typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object"
typeof null // "object" (This is a historical bug in JS)
typeof alert // "function"
4. null vs undefined
undefined: "I don't know what this is yet." It is the default value of uninitialized variables.null: "This is explicitly nothing." It is a value assigned by a programmer to indicate "no value".