Sub topic 2
How Mutation Leads to Bugs
This chapter assumes you are comfortable with JavaScript functions, objects, arrays, and arrow functions. It also assumes you have read the previous chapter, which showed that assigning an object copies a reference rather than the object. Here we follow that fact to its consequences. You will see the most common ways that changing a shared object in place breaks code that seemed correct, and you will learn to spot those patterns before they reach production.
What "mutation" means here
Mutation is any operation that changes an existing object or array in place, instead of producing a new one. Setting a property, deleting a property, and calling push are all mutations. Mutation is a normal part of JavaScript and is not wrong in itself. It becomes a problem when the mutated value is shared. If two parts of a program hold references to the same object, one part can change data the other part relies on, and nothing warns the second part that this happened.
That situation is called aliasing. An alias is a second name for the same underlying value. Every bug in this chapter is a case of aliasing combined with mutation.
Bug pattern 1: functions that mutate their arguments
When you pass an object to a function, the function receives a reference to the caller's object. If the function changes that object, the caller's data changes too.
function applyDiscount(order, percent) {
order.total = order.total * (1 - percent / 100);
return order;
}
const order = { id: 7, total: 100 };
const discounted = applyDiscount(order, 10);
console.log(discounted.total); // 90
console.log(order.total); // 90, the caller's order was changed
console.log(discounted === order); // true, there is only one objectThe name applyDiscount and the return statement suggest that it produces a discounted order and leaves the input alone. A caller who keeps order to show the "original price" next to the discounted one will display 90 twice. Nothing fails at the point of the bug. The wrong value shows up later, somewhere else.
This is the main reason mutation bugs are expensive. The line that causes the problem and the line where it shows up can sit in different files, written by different people.
Bug pattern 2: built-in methods that mutate quietly
Some array methods return a new array and others change the array they are called on. Their names do not tell you which is which, and the mutating ones often also return a value, which makes them look pure.
const scores = [42, 7, 19];
function topScore(list) {
return list.sort((a, b) => b - a)[0];
}
console.log(topScore(scores)); // 42
console.log(scores); // [42, 19, 7], the caller's array was reorderedsort reorders the array in place and returns the same array. Code elsewhere that depends on scores staying in insertion order, such as a chart showing scores by round, is now wrong.
These built-in operations mutate their target:
| Operation | Mutates | Returns |
|---|---|---|
| `push`, `unshift` | the array | new length |
| `pop`, `shift` | the array | removed element |
| `splice` | the array | array of removed elements |
| `sort`, `reverse` | the array | the same array |
| `fill`, `copyWithin` | the array | the same array |
| `arr[i] = v`, `arr.length = n` | the array | the assigned value |
| `obj.key = v`, `delete obj.key` | the object | the value, or `true` |
| `Object.assign(target, ...)` | `target` | `target` |
map, filter, slice, concat, and the ES2023 copying methods all return new arrays. Later chapters cover them in detail.
Bug pattern 3: shared defaults and module-level state
Objects defined once at module level are shared by every caller. If any caller mutates them, every later caller gets the changed version.
const defaultHeaders = { 'Content-Type': 'application/json' };
function buildRequest(url, token) {
const headers = defaultHeaders;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return { url, headers };
}
const a = buildRequest('/private', 'secret-123');
const b = buildRequest('/public');
console.log(b.headers.Authorization); // 'Bearer secret-123'The public request now carries a private token. This is a correctness bug and also a security bug. const headers = defaultHeaders looks like it creates a local value, but it only creates a second name for the shared object. The bug also depends on call order: if /public had been requested first, it would have looked fine. Bugs that depend on order like this tend to pass tests and then fail in production.
Bug pattern 4: history, caches, and snapshots that change after the fact
Undo stacks, caches, and event logs all store a value with the expectation that it stays as it was. If what they store is a reference to a live object, the "snapshot" keeps changing.
const history = [];
const cart = { items: ['apple'] };
history.push(cart); // intended as a snapshot of the cart
cart.items.push('pear'); // the user adds another item
console.log(history[0].items); // ['apple', 'pear'], the snapshot changed
console.log(history[0] === cart); // trueAn undo operation that restores history[0] restores nothing, because the history entry is the current cart. Memoization caches have the same problem: if a cached result object is returned to callers and one of them mutates it, every later cache hit returns the corrupted value.
Bug pattern 5: change detection that misses changes
Many systems decide whether something changed by comparing references with ===. That comparison is cheap, but it only works if changes produce new objects. Mutating an object keeps its reference the same, so the change is invisible.
let lastRendered = null;
function render(state) {
if (state === lastRendered) {
console.log('skipped: nothing changed');
return;
}
lastRendered = state;
console.log('rendered', state.items.length, 'items');
}
const state = { items: [] };
render(state); // rendered 0 items
state.items.push('a');
render(state); // skipped: nothing changed (wrong)This is how React, Redux selectors, memoized components, and many caching layers behave. A common symptom is "I updated the state but the screen did not change." The data did change. The framework could not tell, because the reference stayed the same. A later chapter shows how immutable updates make this comparison reliable.
Bug pattern 6: mutating a collection while iterating it
Changing an array while looping over it shifts the indexes under the loop.
const list = [1, 2, 2, 3];
list.forEach((n, i) => {
if (n === 2) {
list.splice(i, 1);
}
});
console.log(list); // [1, 2, 3], one of the 2s survivedWhen the first 2 at index 1 is removed, the second 2 moves into index 1. The loop then moves on to index 2 and never looks at it. const result = list.filter(n => n !== 2) avoids the problem because it builds a new array and leaves the one it reads from unchanged.
Bug pattern 7: mutation across asynchronous boundaries
Callbacks, promises, and timers run later. If they hold a reference to an object, they see its state at the moment they run, not at the moment they were scheduled.
const job = { id: 1, status: 'pending' };
setTimeout(() => {
console.log(`job ${job.id} was submitted as ${job.status}`);
}, 0);
job.status = 'done';
// Logs: job 1 was submitted as doneIn real code, the delay might be a network request, and the late reader might be an analytics event or an audit log entry. Making a copy when scheduling, or never mutating job, keeps the record accurate.
Why these bugs are hard to find
Each pattern shares a few traits that make debugging slow:
- Action at a distance. The mutation and the symptom are in different places, so a stack trace at the symptom does not point to the cause.
- Order dependence. The outcome depends on which code ran first, so tests that run in a different order may pass.
- No error. JavaScript allows these writes silently. The program keeps running with wrong data.
- Hidden contracts. Whether a function mutates its input is rarely in its name or signature. You have to read its body, and every function it calls.
The last point matters most at scale. In a codebase where any function might mutate, you cannot reason about one function on its own. In a codebase where shared data is never mutated, a value you hold is guaranteed to stay as it is, and that is the guarantee the rest of this tutorial builds.
When mutation is fine
Mutation is safe when no one else can see the value. An array you create inside a function, fill in a loop, and return has no aliases until the function returns. Mutating it during construction is fast and clear. The rule of thumb is: mutate only values you own and have not yet shared. Once a value is passed to a caller, stored in state, cached, or logged, treat it as read-only.
Exercise
A function normalize(user) runs user.email = user.email.toLowerCase(); return user;. A caller does const clean = normalize(formData); showDiff(formData, clean);, where showDiff highlights fields that changed. Why does showDiff never show any differences?
Show answer
normalize mutates the object it receives and returns that same object, so formData and clean are references to one object. showDiff compares the object with itself, and every field matches. The fix is for normalize to return a new object, for example return { ...user, email: user.email.toLowerCase() };.
Exercise
Find the mutation bug: function latest(events) { return events.reverse()[0]; }. Name the method responsible and describe what a caller who reuses events will observe.
Show answer
reverse reverses the array in place and returns the same array. After one call, the caller's events is in reverse order, and calling latest(events) again reverses it back and returns the oldest event. A non-mutating version is events[events.length - 1] or events.at(-1).
Exercise
A component skips rendering when newState === oldState. A handler runs state.todos.push(todo); setState(state);. Explain why the new todo does not appear, and what property the update must have for the check to work.
Show answer
push changes the existing array, and state is still the same object, so newState === oldState is true and the render is skipped. The update must produce a new top-level state object and a new todos array, so that the reference comparison sees a different value.