Arrays
Changing arrays and copies
Know which methods change an array in place — and make a copy when the original is still needed.
Why it exists
Arrays and objects are held by reference: if two parts of a program hold one array, a change in one shows up in the other. That's the source of the sneakiest bugs: a function "just sorted" a list — and elsewhere on screen it changed order too. In React, changing an array in place isn't even noticed: the reference is the same, so the interface doesn't update. So it matters to tell the methods that change an array from the ones that create a new one.
Where it's used
- State in React and other frameworks: it's updated only with new arrays —
setItems([...items, newItem]). - Functions that take an array as an argument and mustn't spoil it for the caller.
- Undo: earlier versions of the data have to be kept.
Syntax
// change the array: push, pop, shift, unshift, splice, sort, reverse, fill
// return a new one: map, filter, slice, concat, flat, toSorted, toReversed, withExamples
const a = [3, 1, 2];
const b = [...a];
b.sort((x, y) => x - y);
a; // → [3, 1, 2]const prices = [3, 1, 2];
const sorted = prices.toSorted((a, b) => a - b);
prices; // → [3, 1, 2]
sorted; // → [1, 2, 3]toSorted leaves the original aloneconst a = [1, 2];
const b = a;
b.push(3);
a; // → [1, 2, 3]const items = [{ qty: 1 }];
const copy = [...items];
copy[0].qty = 5;
items[0].qty; // → 5Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Change in place (mutate): push, pop, shift, unshift, splice, sort, reverse, fill, plus assigning by index arr[0] = …. They work on the same array, and everyone holding a reference to it sees the changes.
Return a new array: map, filter, slice, concat, flat, spread [...arr], and since 2023 toSorted, toReversed, toSpliced and with(i, value) as "safe" versions of the mutating methods.
The copies [...arr] and arr.slice() are shallow: a new array is created, but the objects inside are still shared. Changing copy[0].price changes the original too. For a full copy of nested data there's structuredClone(arr).
const doesn't help here: it forbids assigning another array to the variable, but doesn't stop you changing this one's contents.
Traps
How it differs from…
- Spread
... [...arr] is the shortest way to make a shallow copy of an array.
When to pick something else
Mutation isn't evil in itself. If an array was created inside the function and hasn't gone anywhere yet (say, result in a loop), use push freely — copying it on every step would be slow and pointless. Copy when the data is someone else's or shared.