
The bug you keep shipping
Array.prototype.sort(), reverse(), and splice() mutate the array in place. That sounds convenient until you realize you just reordered the data another component was rendering, or corrupted a cached list you meant to keep immutable.
const scores = [10, 3, 8, 1];
const topThree = scores.sort((a, b) => b - a).slice(0, 3);
console.log(scores); // [10, 8, 3, 1] ← the original is gone
scores is no longer the array you think it is. If that array came from a store, from props, or from a memoized value, you have now mutated shared state — silently.
The ES2023 fix: non-mutating twins
ES2023 shipped copy-returning versions of the destructive methods. They do the same job but hand you a new array and leave the original untouched:
| Destructive | Safe copy |
|————-|———–|
| sort() | toSorted() |
| reverse() | toReversed() |
| splice() | toSpliced() |
| (n/a) | with() — copy-with-replacement |
toSorted — sort without the side effect
const scores = [10, 3, 8, 1];
const ranked = scores.toSorted((a, b) => b - a);
console.log(ranked); // [10, 8, 3, 1]
console.log(scores); // [10, 3, 8, 1] ← unchanged
Use it anywhere you previously wrote arr.slice().sort(...) — toSorted makes the intent explicit instead of hiding it in a defensive copy.
with — replace one element immutably
with(index, value) is the array equivalent of “give me a copy where position index is now value“. It is the immutable counterpart to arr[i] = v.
const todos = ["buy milk", "walk dog", "write tests"];
const updated = todos.with(1, "walk dog (done)");
console.log(updated); // ["buy milk", "walk dog (done)", "write tests"]
console.log(todos); // ["buy milk", "walk dog", "write tests"]
This is the cleanest way to update a single item inside React state without a manual spread:
setTodos(prev => prev.with(idx, newText));
toSpliced — insert, delete, or replace without mutating
toSpliced(start, deleteCount, ...items) mirrors splice() but returns the new array.
const list = ["a", "b", "c", "d"];
list.toSpliced(1, 2); // ["a", "d"] delete 2 from index 1
list.toSpliced(2, 0, "x"); // ["a", "b", "x", "c", "d"] insert
list.toSpliced(0, 1, "z"); // ["z", "b", "c", "d"] replace
Small print
- They return new arrays — the original is safe, but it is a different reference.
===comparisons anduseMemo/useEffectdeps will see a change (usually what you want). - The copy is shallow: nested objects are still shared by reference, exactly like
slice(). - Available in all modern browsers and Node 20+. For legacy targets, transpile with Babel’s ES2023 preset or add a small polyfill.
When to reach for them
Any time you were about to call .slice().sort(), [...arr].reverse(), or spread-then-assign just to avoid mutation — swap in the to* / with form. Less ceremony, zero surprise, and the method name tells the next reader you meant to keep the original intact.