Which array methods change the original array and which return a new one?
push, pop, shift, unshift, splice, sort, reverse and fill change the original. map, filter, slice, concat, flat and the newer toSorted, toReversed and toSpliced return new arrays.
Explain it simply
Some methods edit your notebook, others give you a photocopy. Knowing which is which matters in React state, shared data and anywhere a bug can come from "who changed my array?".
Mutating (edit in place): push, pop, shift, unshift, splice, sort, reverse, fill.
Non-mutating (return new): map, filter, slice, concat, flat, and the ES2023 copies toSorted, toReversed, toSpliced and with.
Spreading first, as in [...arr].sort(), gives you a copy to mutate safely. Note that all of these copies are shallow: the objects inside are still shared.
Example
const a = [3, 1, 2];
const b = a.toSorted();
console.log(a); // Output: [3,1,2]
console.log(b); // Output: [1,2,3]
a.sort();
console.log(a); // Output: [1,2,3]
const c = [1, 2, 3];
const d = c.concat(4);
console.log(c); // Output: [1,2,3]
console.log(d); // Output: [1,2,3,4]
c.push(9);
console.log(c); // Output: [1,2,3,9]What to say in the interview
"push, pop, shift, unshift, splice, sort, reverse and fill mutate. map, filter, slice, concat, flat and the ES2023 toSorted, toReversed and toSpliced return new arrays. When I must keep the original, I use a non-mutating method or copy with spread first."
Common mistakes
- Believing sort returns a new array. It returns the same array, now sorted.
- Assuming a spread copy also copies nested objects. It does not.