What is the difference between primitive and reference types?
The core difference is how values are stored and copied.
Primitives — strings, numbers, booleans, etc. Stored by value; copying makes an independent copy.
Reference types — objects, arrays, functions. Stored by reference; copying copies the pointer, so both names share one object.
Consequence: changing a copied object affects the original — clone it if you need independence.
// Primitives — copy by value
let a = 42;
let b = a; // Copies the value
b = 100;
console.log(a); // 42 — unchanged
// References — copy by reference
let obj1 = { name: 'John' };
let obj2 = obj1; // Copies the reference (same object)
obj2.name = 'Jane';
console.log(obj1.name); // 'Jane' — same object!
// Comparison
console.log(42 === 42); // true (same value)
console.log({ a: 1 } === { a: 1 }); // false (different objects!)
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(arr1 === arr2); // false (different references)
const arr3 = arr1;
console.log(arr1 === arr3); // true (same reference)Primitive b = a copies the value — changing b does not affect a. Reference obj2 = obj1 copies the pointer — both point to the same object, so changing obj2.name changes obj1.name.
Two objects with identical content are not === (different references). Only references to the SAME object are ===.
Primitives: copy value, compare by value. References: copy pointer, compare by reference.
The object comparison gotcha ({} !== {}) is the most tested detail. The obj2 = obj1 aliasing bug (modifying one affects the other) is essential to demonstrate.