Sub topic 1
Why Mutation Causes Bugs: sort, splice, and Index Assignment
Prerequisites
This chapter assumes you know JavaScript arrays and indexing, Array.prototype.sort and Array.prototype.splice, and arrow functions. You should also know that variables holding objects or arrays hold references to them, while primitives are copied by value.
How mutation leaks
sort, splice, and bracket assignment (arr[i] = x) change the array in place. Any other code holding a reference to that array sees the change too. The most common bug is a helper that quietly rewrites its caller's data:
function topScore(list) {
return list.sort((a, b) => b - a)[0];
}
const scores = [40, 100, 1, 5];
console.log(topScore(scores)); // 100
console.log(scores); // [100, 40, 5, 1] (caller's array was reordered)The function is meant to read the data, but it reorders it as a side effect. Code that later depends on the original order, or a UI framework that compares references to detect changes, breaks without any error.
The copying methods added in ES2023
ES2023's "Change Array by Copy" proposal added copying versions of the mutating methods. Each one returns a new array and leaves the original alone.
| Mutating | Copying (ES2023) | Returns |
|---|---|---|
| `sort(cmp)` | `toSorted(cmp)` | new sorted array |
| `reverse()` | `toReversed()` | new reversed array |
| `splice(start, n, ...items)` | `toSpliced(start, n, ...items)` | new array (not the deleted items) |
| `arr[i] = x` | `with(i, x)` | new array with one slot replaced |
Comparators and the default string order
With no comparator, both sort and toSorted convert elements to strings and compare them by UTF-16 code units. So 100 comes before 40, because "1" sorts before "4". A comparator (a, b) => ... returns a negative number if a goes first, a positive number if b goes first, and 0 if their order doesn't matter. For numbers, use (a, b) => a - b for ascending order.
Sorting without mutation with toSorted
toSorted takes the same optional comparator as sort:
const scores = [40, 100, 1, 5];
const mutated = [...scores];
mutated.sort();
console.log(mutated); // [1, 100, 40, 5] (string order)
const sorted = scores.toSorted((a, b) => a - b);
console.log(sorted); // [1, 5, 40, 100]
console.log(scores); // [40, 100, 1, 5] (unchanged)Exercise
Rewrite topScore so it no longer changes the caller's array, and explain what scores.toSorted() (with no comparator) returns for [40, 100, 1, 5].
Show answer
function topScore(list) { return list.toSorted((a, b) => b - a)[0]; } returns 100 and leaves list unchanged. With no comparator, toSorted returns [1, 100, 40, 5], because the elements are compared as strings.