Sub topic 1
Why mutation causes bugs: sort, splice, and index assignment
A mutating method changes the array you call it on. A copying method leaves that array alone and returns a new one. JavaScript has long had both kinds, but three of the most common array operations mutate: sort, splice, and assigning to an index with brackets. This chapter shows how that mutation causes bugs, so the copying methods in later chapters have a clear purpose.
Prerequisites
This chapter assumes you already know:
- JavaScript arrays and zero-based indexing
- How
Array.prototype.sortandArray.prototype.spliceare called - Arrow functions
- That objects and arrays are held by reference, while numbers and strings are primitive values
One array, many names
Assigning an array to a variable does not copy the array. It copies a reference, which is a pointer to the same array in memory. Every variable or parameter that holds that reference sees every change.
const original = [1, 2, 3];
const alias = original;
alias[0] = 99;
console.log(original); // [99, 2, 3]
console.log(alias === original); // truesort changes the caller's data
sort reorders the array in place and returns that same array. A function that sorts its argument therefore changes data it does not own.
const scores = [40, 100, 1, 5];
function topScore(list) {
return list.sort((a, b) => b - a)[0];
}
console.log(topScore(scores)); // 100
console.log(scores); // [100, 40, 5, 1] (the caller's order is gone)Nothing in the name topScore warns the caller. Code that later relies on the original order, such as matching scores to players by position, now reads the wrong values.
splice returns the wrong thing for many uses
splice removes or inserts elements in place. It returns the deleted elements, not the updated array. Developers often expect the opposite.
const queue = ["a", "b", "c", "d"];
const result = queue.splice(1, 2);
console.log(result); // ["b", "c"] (the removed items)
console.log(queue); // ["a", "d"] (the original was changed)If you write const remaining = queue.splice(1, 2), you get the two items you meant to throw away, and queue has changed without notice.
Index assignment can grow the array
Bracket assignment mutates too, and it never checks bounds. Writing past the end makes the array longer and leaves holes, which are empty slots with no value.
const items = ["x", "y"];
items[4] = "z";
console.log(items.length); // 5
console.log(2 in items); // false (index 2 is a hole)Mutation breaks change detection
UI libraries such as React decide whether to re-render by checking whether a value's reference changed. If you mutate an array, the reference stays the same, so the library sees no change.
let state = [3, 1, 2];
const previous = state;
state.sort((a, b) => a - b);
console.log(state); // [1, 2, 3]
console.log(state === previous); // true (looks unchanged to a reference check)Common errors
| Mistake | What actually happens |
|---|---|
| Sorting a function parameter | The caller's array is reordered |
| Using the return value of `splice` as the new array | You get the deleted elements |
| `arr[i] = v` with `i` past the end | The array grows and gets holes |
| Mutating state, then comparing references | The change is never detected |
The usual workaround is to copy first with [...arr] and then mutate the copy. That works, but it is easy to forget. ES2023 added methods that copy for you, and the next chapter introduces them.
Exercise
After running const a = [5, 2, 8]; const b = a; const c = b.splice(0, 1);, what are the values of a, b, and c?
Show answer
a and b are both [2, 8], because they reference the same array and splice mutated it. c is [5], the array of removed elements.
Exercise
A function latest(list) returns list.sort((x, y) => y.date - x.date)[0]. Why could this cause a bug elsewhere, and what is the simplest pre-ES2023 fix?
Show answer
sort reorders the caller's array in place, so any other code using that array sees the new order. Sort a copy instead: [...list].sort((x, y) => y.date - x.date)[0].