Sub topic 6
Working Without Mutation
This chapter assumes you know core JavaScript syntax, spread and rest syntax, and how object references work. It also assumes you have read the earlier chapter on pure functions. To run the examples you need Node.js 20 or later, because some of them use array methods added in ES2023.
Mutation means changing a value in place: setting a property, pushing onto an array, or sorting an array where it sits. Immutability means you never do that. To "change" data, you build a new value that contains the change and leave the original alone. This chapter shows how to do that in everyday JavaScript and where it tends to go wrong.
Why mutation causes bugs
In JavaScript, objects and arrays are passed by reference. Two variables can point at the same object. If either one mutates it, both see the change, and the second one never asked for it.
const defaults = { theme: 'dark', fontSize: 14 };
function applyLargeText(settings) {
settings.fontSize = 20; // mutates the caller's object
return settings;
}
const userSettings = applyLargeText(defaults);
console.log(userSettings.fontSize); // 20
console.log(defaults.fontSize); // 20 (the defaults were changed too)
console.log(userSettings === defaults); // trueapplyLargeText looks harmless, but every later reader of defaults now gets wrong data. In a large codebase you cannot tell which function did it without tracing every reference. Immutable updates remove this whole class of bug. A value that nobody can change can be shared safely.
Immutability also makes change detection cheap. If updates always produce new objects, then oldState !== newState tells you something changed. You do not need a deep comparison. UI libraries such as React rely on this, which is why mutating state in place stops components from re-rendering.
`const` is not immutability
A common mistake is assuming const protects the value. It only stops the variable from being reassigned. It does not protect the object the variable points to.
const config = { retries: 3 };
config.retries = 10; // allowed: the object is mutable
console.log(config); // { retries: 10 }
// config = {}; // TypeError: Assignment to constant variable.Use const by default anyway. It keeps a name tied to one value. Just don't treat it as a guarantee about the contents.
Updating objects with spread
Object spread copies an object's own enumerable properties into a new object. Properties written after the spread override the copied ones.
const user = { name: 'Ada', role: 'admin', active: true };
const renamed = { ...user, name: 'Grace' }; // change a field
const withEmail = { ...user, email: '[email protected]' }; // add a field
const { role, ...withoutRole } = user; // remove a field
console.log(user); // { name: 'Ada', role: 'admin', active: true }
console.log(renamed); // { name: 'Grace', role: 'admin', active: true }
console.log(withEmail); // { name: 'Ada', role: 'admin', active: true, email: '[email protected]' }
console.log(withoutRole); // { name: 'Ada', active: true }Order matters. { name: 'Grace', ...user } keeps 'Ada', because the spread comes last and overwrites name.
The shallow copy trap
Spread copies one level deep. Nested objects and arrays are copied by reference, so the copy and the original still share them.
const original = { name: 'Ada', tags: ['math'] };
const copy = { ...original };
copy.name = 'Grace'; // safe: top-level property
copy.tags.push('code'); // unsafe: tags is shared
console.log(original.name); // Ada
console.log(original.tags); // [ 'math', 'code' ]This is the most common immutability bug in real code. To update a nested value, copy every level on the path from the root down to the value you change.
const state = {
user: { name: 'Ada', prefs: { theme: 'dark', lang: 'en' } },
items: [1, 2, 3]
};
const next = {
...state,
user: {
...state.user,
prefs: { ...state.user.prefs, theme: 'light' }
}
};
console.log(state.user.prefs.theme); // dark
console.log(next.user.prefs.theme); // light
console.log(state.items === next.items); // true (untouched branch is shared)
console.log(state.user.prefs === next.user.prefs); // false (changed branch is new)The unchanged items array is reused rather than copied. This is called structural sharing. The new value copies only the path that changed and points to everything else, so you save memory and time and keep cheap === checks.
Updating arrays without mutating them
Many familiar array methods mutate in place. ES2023 added copying versions of the worst offenders. Check every method against this table.
| Task | Mutating (avoid) | Non-mutating |
|---|---|---|
| Add to end | `push` | `[...arr, x]` or `arr.concat(x)` |
| Add to start | `unshift` | `[x, ...arr]` |
| Remove by index | `splice(i, 1)` | `arr.toSpliced(i, 1)` or `arr.filter((_, j) => j !== i)` |
| Insert at index | `splice(i, 0, x)` | `arr.toSpliced(i, 0, x)` |
| Replace at index | `arr[i] = x` | `arr.with(i, x)` |
| Sort | `sort` | `arr.toSorted(cmp)` |
| Reverse | `reverse` | `arr.toReversed()` |
| Fill | `fill` | `Array.from({ length: n }, () => x)` |
const list = ['a', 'b', 'c'];
console.log([...list, 'd']); // [ 'a', 'b', 'c', 'd' ]
console.log(list.toSpliced(1, 1)); // [ 'a', 'c' ]
console.log(list.toSpliced(1, 0, 'x'));// [ 'a', 'x', 'b', 'c' ]
console.log(list.with(1, 'B')); // [ 'a', 'B', 'c' ]
console.log(list.toReversed()); // [ 'c', 'b', 'a' ]
console.log(list); // [ 'a', 'b', 'c' ] (unchanged)
// Update one object in an array of objects
const todos = [{ id: 1, done: false }, { id: 2, done: false }];
const toggled = todos.map((t) => (t.id === 2 ? { ...t, done: !t.done } : t));
console.log(todos[1].done, toggled[1].done); // false true
console.log(todos[0] === toggled[0]); // true (shared)Deep copies with `structuredClone`
Sometimes you really do need a fully independent copy, for example before handing data to code you don't trust. structuredClone (Node 17+, all modern browsers) copies at every depth. It also handles Date, Map, Set, and circular references.
const original = { when: new Date(0), tags: new Set(['a']), nested: { n: 1 } };
const clone = structuredClone(original);
clone.nested.n = 99;
clone.tags.add('b');
console.log(original.nested.n, original.tags.size); // 1 1
console.log(clone.when instanceof Date); // true
try {
structuredClone({ fn: () => 1 });
} catch (err) {
console.log(err.name); // DataCloneError
}It has limits. It throws on functions and DOM nodes. Class instances come back as plain objects without their prototype, so their methods are gone. Avoid JSON.parse(JSON.stringify(x)): it silently turns dates into strings and drops undefined values. Deep copying on every update also wastes work, so prefer path copying with structural sharing for routine state changes.
Enforcing immutability with `Object.freeze`
The techniques so far depend on discipline. Object.freeze makes the runtime enforce it. A frozen object rejects new properties, deletions, and changes to existing properties. In strict mode, which ES modules and classes use automatically, those attempts throw an error. In sloppy-mode scripts they fail silently, and that makes them hard to notice.
'use strict';
const deepFreeze = (obj) => {
for (const value of Object.values(obj)) {
if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return Object.freeze(obj);
};
const shallow = Object.freeze({ limits: { max: 5 } });
shallow.limits.max = 50; // allowed: freeze is shallow
console.log(shallow.limits.max); // 50
const deep = deepFreeze({ limits: { max: 5 } });
try {
deep.limits.max = 50;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(deep.limits.max); // 5Freezing helps most in development and tests, where it catches accidental mutation at the line that causes it. Deep-freezing large structures on every update costs time, so many teams freeze only in development builds. TypeScript's readonly and Readonly<T> give similar protection at compile time with no runtime cost.
Where local mutation is fine
Immutability matters at boundaries, meaning the values other code can see. Mutating a value that you created inside a function, and that never escapes until it is finished, can't surprise anyone. The function is still pure from the outside.
const indexById = (items) => {
const result = {}; // local, nobody else can see it
for (const item of items) result[item.id] = item;
return result;
};
console.log(indexById([{ id: 'a' }, { id: 'b' }])); // { a: { id: 'a' }, b: { id: 'b' } }This version runs in linear time. A version that spreads the accumulator on every step ({ ...acc, [item.id]: item }) copies the whole object each time, which makes it quadratic and slow for large inputs. Be strict about not mutating shared data, and use local mutation when it makes the code faster or clearer.
Exercise
A teammate writes const latest = posts.sort((a, b) => b.date - a.date)[0]; inside a render function that receives posts as a prop. What goes wrong, and how do you fix it?
Show answer
sort reorders the caller's posts array in place, so every other user of that array sees the new order, and change detection that compares references does not notice anything. Use posts.toSorted((a, b) => b.date - a.date)[0] or [...posts].sort(...)[0]. To get only the latest post without sorting, use posts.reduce((best, p) => (p.date > best.date ? p : best)).
Exercise
Given const state = { cart: { items: [{ id: 1, qty: 1 }, { id: 2, qty: 3 }] } };, write an expression that produces a new state where item 2 has qty: 4, without mutating state. Which objects end up shared between the old and new state?
Show answer
const next = { ...state, cart: { ...state.cart, items: state.cart.items.map((i) => (i.id === 2 ? { ...i, qty: 4 } : i)) } }; The root, cart, the items array, and item 2 are all new objects. Item 1 is the same object in both states, so state.cart.items[0] === next.cart.items[0] is true.
Exercise
Why does Object.freeze(config) fail to stop config.servers.push('x'), and what fails silently if the code runs as a non-module script without 'use strict'?
Show answer
Object.freeze is shallow. It freezes config's own properties, but config.servers points to an array that is still mutable, so push works. Use a recursive deep freeze to protect it. In sloppy mode, assignments to a frozen object's properties, such as config.port = 1, are ignored without any error, so the bug goes unnoticed. In strict mode they throw a TypeError.