Immutability Patterns in JavaScript

JavaScript’s objects and arrays are mutable by default, but treating state as immutable (never modifying in place, always creating a new copy) prevents a whole class of “who changed this and when” bugs.

// Mutating (avoid for shared/tracked state)
const user = { name: 'Alice', age: 30 };
user.age = 31; // any other reference to <code>user</code> sees this change too

// Immutable update: spread creates a new object
const updatedUser = { ...user, age: 31 }; // original <code>user</code> untouched

// Arrays: avoid mutating methods for shared state
const items = [1, 2, 3];
items.push(4);          // mutates in place - avoid for tracked state
const newItems = [...items, 4]; // creates a new array instead

// Object.freeze enforces immutability at runtime
const frozen = Object.freeze({ x: 1 });
frozen.x = 2; // silently fails (or throws in strict mode)

Why This Matters

Immutability makes change detection trivial (a simple reference comparison, oldState !== newState