Sub topic 1
Why mutation causes bugs: sort, splice, and index assignment
JavaScript arrays are objects, and objects are passed around by reference. When a method changes an array in place, every variable, function, and component that holds a reference to that array sees the change, whether it wanted to or not. This chapter covers the three most common sources of accidental mutation: sort, splice, and bracket assignment (arr[i] = value). It also covers the habits developers used to avoid them before ES2023.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript arrays and zero-based indexing
Array.prototype.sortandArray.prototype.splice, including their arguments- Arrow functions such as
(a, b) => a - b - The difference between primitive values (numbers, strings) and object references
If you know that const a = [1]; const b = a; gives you two names for one array, you have the model this chapter builds on.
The core problem: one array, many owners
A mutating method changes the array it is called on. A copying method leaves that array alone and returns a new one. The distinction matters because an array rarely has a single owner. A function receives it as an argument. A module exports it. A cache stores it. A UI framework keeps the previous version of it to detect changes.
Copying with const b = a duplicates the reference, not the array. Each mutating call therefore acts on shared data.
Bug 1: sort changes the caller's data
sort reorders the array in place and returns that same array. Because it returns something, it looks like a function that produces a new value. It doesn't.
const leaderboard = [40, 100, 1, 5];
function topScore(scores) {
return scores.sort((a, b) => b - a)[0];
}
console.log(topScore(leaderboard)); // 100
console.log(leaderboard); // [100, 40, 5, 1] (caller's array was reordered)The function name says "read the top score", but it rewrote the caller's array. Any code that relied on leaderboard keeping insertion order, such as a "most recent first" display, is now wrong. The bug shows up far from where it was caused.
The return value adds a second trap:
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(sorted === original); // true
console.log(original); // [1, 2, 3]A developer who writes const sorted = original.sort() usually believes they now have two arrays. They have one array with two names.
The default comparator makes it worse
Called without a comparator, sort converts elements to strings and compares them by UTF-16 code units. Numbers end up in string order:
const scores = [40, 100, 1, 5];
scores.sort();
console.log(scores); // [1, 100, 40, 5]This mistake combined with mutation is a common pair. A forgotten comparator silently corrupts shared data instead of producing one wrong local result. Comparators get their own chapter later.
Bug 2: splice returns the wrong thing
splice(start, deleteCount, ...items) removes and inserts elements in place. It returns an array of the deleted elements, not the resulting array. Developers who expect a functional style often write this:
const queue = ["a", "b", "c", "d"];
const withoutB = queue.splice(1, 1);
console.log(withoutB); // ["b"] (the removed element, not the remaining list)
console.log(queue); // ["a", "c", "d"] (original changed)This one line contains two bugs. withoutB holds the wrong data, and queue was modified. If queue came from props, a store, or a shared module, other code now sees an array that is one element shorter.
Insertion has the same shape. splice(1, 0, "x") returns [], which surprises people who expected the array with "x" added.
Bug 3: index assignment through an alias
Bracket assignment is the simplest mutation and the easiest to overlook:
const defaults = ["light", "medium", "en"];
const userSettings = defaults;
userSettings[0] = "dark";
console.log(defaults[0]); // "dark" (the shared defaults were changed)The developer meant to customize one user's settings and changed the defaults for everyone.
Index assignment also allows writes past the end of the array. JavaScript doesn't throw. It grows the array and leaves holes:
const slots = [1, 2, 3];
slots[5] = 6;
console.log(slots.length); // 6
console.log(3 in slots); // false (index 3 is a hole, not undefined)
console.log(slots); // Node prints [ 1, 2, 3, <2 empty items>, 6 ]An off-by-one index turns into a quiet change of length and a sparse array, instead of an error at the line that caused it. The ES2023 with method, covered later, throws a RangeError in this case.
Bug 4: change detection sees nothing
Many systems decide whether data changed by comparing references with !==. React's useState, Redux selectors, React.memo, and memoization libraries all work this way. Mutation keeps the reference, so the change is invisible to them:
const store = { items: [3, 1, 2] };
function hasChanged(prev, next) {
return prev !== next;
}
const before = store.items;
store.items.sort((a, b) => a - b);
console.log(store.items); // [1, 2, 3]
console.log(hasChanged(before, store.items)); // falseThe data changed, but the check says it didn't. In React this shows up as a component that doesn't re-render after items.sort() followed by setItems(items). In Redux it shows up as a reducer that "works" while the connected components keep showing stale data, and time-travel debugging shows history entries that are all identical.
Bug 5: frozen or read-only arrays throw
If an array is frozen, for example by Immer in development mode, by a library, or by your own Object.freeze, mutating methods fail:
const frozen = Object.freeze([3, 1, 2]);
try {
frozen.sort((a, b) => a - b);
} catch (err) {
console.log(err instanceof TypeError); // true
}sort and splice always throw on a frozen array. Bracket assignment throws in strict mode, which includes ES modules and classes. In sloppy-mode scripts it fails silently, which is the worse outcome.
The pre-ES2023 workarounds
Before ES2023, the fix was to copy first and then mutate the copy:
| Goal | Mutating code | Copy-first workaround |
|---|---|---|
| Sort | `arr.sort(cmp)` | `[...arr].sort(cmp)` or `arr.slice().sort(cmp)` |
| Reverse | `arr.reverse()` | `[...arr].reverse()` |
| Remove/insert | `arr.splice(i, n, x)` | `[...arr.slice(0, i), x, ...arr.slice(i + n)]` |
| Replace one item | `arr[i] = v` | `arr.map((el, j) => (j === i ? v : el))` |
These work, but they have costs:
- Forgetting the copy is easy.
[...arr].sort()andarr.sort()differ by four characters, and code review often misses that difference. - The splice workaround is hard to read. Two
slicecalls and a spread hide the intent, and off-by-one errors are common. - The
mapworkaround hides bad indices. An out-of-range index silently returns an unchanged copy. - Negative indices need manual math.
arr.length - 1appears throughout the code.
What ES2023 changes
ES2023 added copying versions of the mutating methods directly to Array.prototype:
| Mutating | Copying (ES2023) |
|---|---|
| `sort(cmp)` | `toSorted(cmp)` |
| `splice(start, n, ...items)` | `toSpliced(start, n, ...items)` |
| `arr[i] = v` | `with(i, v)` |
| `reverse()` | `toReversed()` |
Each copying method takes the same arguments as its mutating counterpart, returns a new array, and leaves the original unchanged. toSpliced returns the resulting array, not the deleted elements. The following chapters cover each method.
Exercises
Exercise
What do the two console.log calls print, and why? const a = [10, 9, 1]; const b = a.sort(); console.log(b === a); console.log(a);
Show answer
It prints true, then [1, 10, 9]. sort reorders the array in place and returns the same array, so b and a are one array under two names. With no comparator, sort compares elements as strings, so "10" comes before "9".
Exercise
A developer writes const remaining = tasks.splice(0, 1) to get every task except the first. What goes wrong?
Show answer
remaining holds a one-element array with the removed first task, not the rest of the list. Also, tasks itself is mutated and loses its first element, which affects every other holder of that reference.
Exercise
A React component calls items.sort(), then setItems(items), and the screen does not update. Explain the cause.
Show answer
sort mutated the existing array and kept its reference. React compares the old and new state by reference, sees the same array, and skips the re-render. Passing a new array, such as [...items].sort(cmp) or items.toSorted(cmp), fixes it.
Exercise
What are the length of arr and the value of 2 in arr after const arr = ["x"]; arr[3] = "y";?
Show answer
The length is 4 and 2 in arr is false. Assigning past the end grows the array and leaves indices 1 and 2 as holes instead of throwing an error.