What is the difference between primitive and reference types in assignment and comparison?
Type determines how values are assigned and compared.
Assignment — primitives copy the value (independent); objects copy the reference (shared).
Comparison — primitives compare by value; objects compare by identity, so identical contents aren't equal.
That's why { a: 1 } === { a: 1 } is false — they're different references despite identical contents.
// Primitive — copy by value
let x = 10;
let y = x; // Copy value
y = 20;
console.log(x); // 10 — unchanged
// Reference — copy by pointer
let arr1 = [1, 2, 3];
let arr2 = arr1; // Copy pointer (same array!)
arr2.push(4);
console.log(arr1); // [1, 2, 3, 4] — affected!
// Comparison
console.log(10 === 10); // true (same value)
console.log([1,2] === [1,2]); // false (different objects)
console.log({} === {}); // false
const a = [1, 2];
const b = a;
console.log(a === b); // true (same reference)Primitive y = x copies the value — changing y does not affect x. Reference arr2 = arr1 copies the pointer — both point to the same array, so push affects both.
Two identical-looking objects/arrays are not === (different references). Only same-object references are ===.
The arr2 = arr1 aliasing bug (push affects both) is the most tested scenario. Identical objects {} === {} being false is counterintuitive for beginners.
This is fundamental to understanding JS behavior with objects.