Sub topic 2
How Mutation Leads to Bugs
This chapter assumes you know JavaScript variables, functions, and scope, and that you can work with objects and arrays. It also builds on the previous chapter, which showed that objects and arrays are passed around by reference. Here you will see the bugs that reference semantics causes when code changes shared data in place.
To mutate a value means to change it in place: you push to an array, assign to a property, or call a method such as sort that rewrites the array it is called on. Mutation is fine when only one piece of code can reach the value. Bugs appear when the value is shared, because every holder of the reference sees the change, including code that never asked for it.
Bug 1: A function changes its caller's data
The most common case is a function that mutates an argument. In this example, sort reorders the array it is called on, so the caller's array changes as well.
function topScores(scores, n) {
return scores.sort((a, b) => b - a).slice(0, n);
}
const scores = [42, 97, 15, 88];
const best = topScores(scores, 2);
console.log(best); // [97, 88]
console.log(scores); // [97, 88, 42, 15], the caller's order is lostNothing in the name topScores suggests it rearranges its input. If scores was meant to stay in insertion order, for example to show a timeline, that view is now wrong. The cause is in a different function from where the symptom shows up.
Bug 2: Leaking internal state
A module that returns its internal array gives every caller write access to that array.
function createCart() {
const items = [];
return {
add(item) { items.push(item); },
getItems() { return items; },
total() { return items.reduce((sum, i) => sum + i.price, 0); }
};
}
const cart = createCart();
cart.add({ name: 'Book', price: 20 });
const visible = cart.getItems();
visible.length = 0; // the caller thinks it is clearing its own list
console.log(cart.total()); // 0, the cart itself was emptiedThe closure hides the items variable, but it does not hide the array. Once the reference leaves the module, the module cannot protect its invariants.
Bug 3: Change detection stops working
Many tools decide whether data changed by comparing references with ===. A later chapter covers this technique in detail. Mutation defeats it, because the reference stays the same while the contents change.
const state = { items: ['a'] };
const before = state.items;
state.items.push('b');
console.log(before === state.items); // true, so the change looks like no change
console.log(before); // ['a', 'b'], the "old" snapshot changed tooThere are two problems here. A UI library that skips re-rendering when references match will show stale data. Any code that kept before as a history entry, for example for undo, has lost the old value.
Common patterns at a glance
| Pattern | Example | Symptom |
|---|---|---|
| Mutating an argument | `arr.sort()`, `obj.x = 1` inside a helper | Caller's data changes unexpectedly |
| Returning internal state | `getItems() { return items; }` | Outside code breaks module invariants |
| Mutating shared state | `state.items.push(x)` | Stale UI, broken undo, equal references |
| Shared defaults | Mutating a module-level `DEFAULTS` object | Later calls inherit earlier changes |
The next chapters show how to avoid these bugs. Instead of changing existing values, you create new ones.
Exercise
A helper function addTag(user, tag) { user.tags.push(tag); return user; } is called as const updated = addTag(currentUser, 'admin'). Afterward, a check updated !== currentUser is used to decide whether to save. Name two problems with this code.
Show answer
First, the helper mutates currentUser.tags, so the caller's original object changes and any earlier copy of currentUser now includes 'admin'. Second, it returns the same reference, so updated === currentUser and the change-detection check reports no change, which means the save is skipped.
Exercise
Which of these calls mutate the array they are called on: map, sort, filter, reverse, slice, splice?
Show answer
sort, reverse, and splice mutate the array. map, filter, and slice return a new array and leave the original unchanged.