Sub topic 4
Which Methods Change Your Array?
This chapter assumes you know let and const, can write arrow functions, understand that objects are accessed by reference, and can run code in Node.js or a browser console. You should also know how to create an array and read elements by index.
Every array method does one of two things to the array you call it on. A mutating method changes that array in place. A non-mutating method leaves it alone and returns something new, such as a new array, a single value, or a boolean. Most array bugs in real code come from mixing the two up: you expect a fresh copy and get a modified original, or you expect a change and get back an unused new array.
Why mutation matters: arrays are shared by reference
A variable that holds an array does not hold the elements themselves. It holds a reference to one array object in memory. If you assign that variable to another variable, or pass it to a function, you copy the reference. You do not copy the array.
const original = [3, 1, 2];
const alias = original;
alias.push(4);
console.log(original); // [3, 1, 2, 4]
console.log(alias === original); // true (same array object)push mutated the single array that both names point to. This also shows that const does not protect an array's contents. const only stops you from reassigning the variable to a different value. Methods can still change the array it points to.
The mutating methods
The set of mutating methods is small and fixed, so you can learn it by heart. Treat every other built-in array method as non-mutating.
| Operation | Mutates? | Returns | Non-mutating alternative |
|---|---|---|---|
| `push(x)` | Yes | New length | `[...arr, x]` or `arr.concat(x)` |
| `pop()` | Yes | Removed element | `arr.slice(0, -1)` |
| `shift()` | Yes | Removed element | `arr.slice(1)` |
| `unshift(x)` | Yes | New length | `[x, ...arr]` |
| `splice(i, n, ...items)` | Yes | Array of removed elements | `arr.toSpliced(i, n, ...items)` |
| `sort(fn)` | Yes | The same array | `arr.toSorted(fn)` |
| `reverse()` | Yes | The same array | `arr.toReversed()` |
| `fill(v, start, end)` | Yes | The same array | `arr.map(() => v)` or `Array.from` |
| `copyWithin(t, s, e)` | Yes | The same array | No direct equivalent |
| `arr[i] = v` | Yes | `v` | `arr.with(i, v)` |
| `arr.length = n` | Yes | `n` | `arr.slice(0, n)` |
The non-mutating methods include map, filter, reduce, slice, concat, flat, flatMap, join, find, includes, indexOf, some, every, forEach, and the ES2023 copying methods toSorted, toReversed, toSpliced, and with. Later chapters cover each group in detail. This chapter is about telling the two kinds apart.
Read the return value
The return value is the fastest way to tell what a method did. Mutating methods often return something other than the array you might expect, and that catches people out.
const nums = [3, 1, 2];
const newLength = nums.push(5);
console.log(newLength); // 4, not an array
const sorted = nums.sort((a, b) => a - b);
console.log(sorted); // [1, 2, 3, 5]
console.log(sorted === nums); // true: sort returned the original, now changed
const nums2 = [3, 1, 2];
const sortedCopy = nums2.toSorted((a, b) => a - b);
console.log(sortedCopy); // [1, 2, 3]
console.log(nums2); // [3, 1, 2]
console.log(sortedCopy === nums2); // falseA common mistake is writing const result = arr.push(x) and then treating result as an array. A second mistake is const sorted = arr.sort() with the belief that arr stays as it was. Because sort and reverse return the same array, the code looks like it produced a copy, but it didn't.
The reverse mistake also happens: you call a non-mutating method and throw away its result.
const prices = [10, 20, 30];
prices.map(p => p * 2); // result discarded
console.log(prices); // [10, 20, 30]
const doubled = prices.map(p => p * 2);
console.log(doubled); // [20, 40, 60]If a non-mutating method's return value is not assigned, returned, or passed on, the call almost always does nothing useful.
Side effects through function arguments
Mutation is most dangerous when it happens far from where the array was created. A function that receives an array gets a reference, so any mutating call inside it changes the caller's data.
function topScore(scores) {
return scores.sort((a, b) => b - a)[0];
}
const scores = [72, 95, 88];
console.log(topScore(scores)); // 95
console.log(scores); // [95, 88, 72]: the caller's order is goneThe function answers correctly, but it also reorders the caller's array as a hidden side effect. Fix it by working on a copy, or by using a method that does not sort at all:
function topScoreSafe(scores) {
return scores.toSorted((a, b) => b - a)[0];
}
function topScoreFast(scores) {
return Math.max(...scores);
}
const scores = [72, 95, 88];
console.log(topScoreSafe(scores)); // 95
console.log(topScoreFast(scores)); // 95
console.log(scores); // [72, 95, 88]As a rule, a function should not mutate an array it was given unless its name and documentation say it does, as with a function named sortInPlace.
Copies are shallow
A non-mutating method gives you a new outer array. The elements are copied as values, and when an element is an object, the copied value is a reference to that same object. Spread, slice, concat, toSorted, filter, and the rest all make shallow copies.
const users = [{ name: 'Ana', active: true }];
const copy = [...users];
console.log(copy === users); // false: different arrays
console.log(copy[0] === users[0]); // true: same object inside
copy[0].active = false;
console.log(users[0].active); // false: the original changed tooTo change an element without touching the original, build a new object for it:
const users = [{ name: 'Ana', active: true }];
const updated = users.map(u => ({ ...u, active: false }));
console.log(users[0].active); // true
console.log(updated[0].active); // falseFor deeply nested data where you need a fully independent copy, structuredClone(users) copies every level. It is available in Node.js 17+ and modern browsers. It costs more than a shallow copy and cannot clone functions.
Choosing between mutating and copying
Both styles have a place. Mutation does not allocate a new array, which helps in tight loops over large data or when you build up a local array that nobody else can see yet. Copying keeps data predictable. It is the expected style when the array is shared: state in UI frameworks such as React, function arguments, cached results, or values held by more than one module.
A local array that you build and return is a typical safe case for mutation:
function range(n) {
const result = [];
for (let i = 0; i < n; i++) {
result.push(i); // safe: no one else can see result yet
}
return result;
}
console.log(range(4)); // [0, 1, 2, 3]Checking whether a method mutated
If you are unsure about a method, test it in the console. Keep a reference to the original, call the method, then compare both the contents and the identity:
const before = [3, 1, 2];
const snapshot = [...before];
const result = before.reverse();
console.log(result === before); // true
console.log(JSON.stringify(before) === JSON.stringify(snapshot)); // false: it mutatedWhen the result is the same object and the contents differ from the snapshot, the method mutated the array in place.
Exercise
After this code runs, what are the values of a, b, and c? const a = [4, 2, 9]; const b = a.toReversed(); const c = a.sort((x, y) => x - y);
Show answer
a is [2, 4, 9] because sort mutates it. b is [9, 2, 4], a copy that was reversed before the sort ran. c is [2, 4, 9] and is the same object as a (c === a is true), because sort returns the original array.
Exercise
The function function withoutFirst(list) { list.shift(); return list; } returns the right result, but callers report that their data loses its first item. Rewrite it so the caller's array is left unchanged.
Show answer
Use a non-mutating method that returns a new array: function withoutFirst(list) { return list.slice(1); }. slice(1) copies every element from index 1 onward and leaves list as it was. shift removed the first element from the caller's array, because the function received a reference to that array, not a copy.