Glossary / Immutability
Immutability
Immutability means a value cannot be changed after creation, or that code treats it as stable and creates a new value for each update. JavaScript primitives are immutable; ordinary objects and arrays are mutable by default. Immutable state transitions make change explicit, support predictable history and memoization, and reduce accidental shared-state coupling.
Binding, object, and structural sharing
const current = { user: { name: "Ada" }, theme: "light" };
const next = { ...current, user: { ...current.user, name: "Grace" } };
const protects only the binding; it does not freeze the object. Object.freeze prevents certain changes to own properties but is shallow and does not freeze nested objects or all internal slots. Persistent data structures use structural sharing: create new nodes along changed paths while reusing unchanged subtrees. This helps preserve identity signals without copying everything.
Immutability has costs: allocations, garbage collection, and sometimes more complex update code. It is not always faster or inherently safer. Use it where state history, change detection, concurrency, or ownership makes the tradeoff valuable. Keep mutable state local and encapsulated when mutation is simpler and cannot leak unexpectedly.
Interview questions
- Does const make an object immutable? No; it prevents rebinding only.
- Is Object.freeze deep? No.
- What is structural sharing? Reusing unchanged substructure while creating new nodes for changed paths.
- Is immutability always faster? No; allocation and copying costs depend on data shape and update frequency.