JavaScript is a dynamically typed language. Data types are categorized into two main groups: Primitive Types (stored directly in stack memory by value) and Reference Types (stored in heap memory and accessed via memory addresses).
flowchart TD
Types["JavaScript Data Types"] --> Primitives["Primitive Types (Passed by Value - Stack)"]
Types --> Reference["Reference Types (Passed by Reference - Heap)"]
Primitives --> P1["String"]
Primitives --> P2["Number"]
Primitives --> P3["BigInt"]
Primitives --> P4["Boolean"]
Primitives --> P5["Undefined"]
Primitives --> P6["Null"]
Primitives --> P7["Symbol"]
Reference --> R1["Object"]
Reference --> R2["Array"]
Reference --> R3["Function"]
Reference --> R4["Date / RegExp"]
| Property | Primitive Types | Reference Types |
|---|---|---|
| Storage | Stack Memory | Heap Memory (Pointer stored in Stack) |
| Immutability | Value itself is immutable | Properties/elements are mutable |
| Comparison | Compared by Value (5 === 5) |
Compared by Memory Address ({} === {} is false) |
| Copying | Copying creates an independent value copy | Copying duplicates reference pointer |
// Demonstrating Primitives vs Reference Types
// 1. Primitive Type Copy (Passed by Value)
let originalPrice = 100;
let copiedPrice = originalPrice; // Independent copy
copiedPrice = 150;
console.log(`Original: ${originalPrice}, Copied: ${copiedPrice}`); // 100, 150
// 2. Reference Type Copy (Passed by Memory Reference)
const originalUser = { id: 1, name: "Alex" };
const copiedUser = originalUser; // Copies pointer address
copiedUser.name = "Maksudur"; // Mutates shared heap object!
console.log("Original User Name:", originalUser.name); // "Maksudur" (Mutated!)
// 3. Creating a Shallow Copy to break reference coupling
const clonedUser = { ...originalUser }; // Spread operator shallow clone
clonedUser.name = "Sarah";
console.log("Original User Name:", originalUser.name); // "Maksudur" (Protected!)
console.log("Cloned User Name:", clonedUser.name); // "Sarah"
// 4. Symbol Primitive (Unique Identifier)
const idSym1 = Symbol("id");
const idSym2 = Symbol("id");
console.log(`Symbol Comparison (idSym1 === idSym2): ${idSym1 === idSym2}`); // false
structuredClone(): When copying objects/arrays, create shallow copies ({...obj}) or deep clones (structuredClone(obj)) to avoid unintended mutation bugs.typeof null Mystery: typeof null returns "object" due to a historical bug in JavaScript's original implementation. Use val === null to check for null values.Explain why [] === [] evaluates to false in JavaScript.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.