EasyArrays📖 Theory Question

What are immutable array operations and the new ES2023 methods?

💡

Hint

toSorted, toReversed, toSpliced, with — immutable versions of mutating methods

Full Answer

Many array methods mutate the original. Always be aware of which do and which don't:

Mutating (change original): sort, reverse, splice, push, pop, shift, unshift, fill

Non-mutating (return new): map, filter, slice, concat, flat, flatMap, reduce

const arr = [3, 1, 2];

// Old pattern — copy first to avoid mutation
const sorted = [...arr].sort((a, b) => a - b); // arr unchanged

// ES2023 — built-in immutable versions
arr.toSorted((a, b) => a - b);  // [1, 2, 3] — arr still [3, 1, 2]
arr.toReversed();               // [2, 1, 3] — arr still [3, 1, 2]
arr.toSpliced(1, 1, 9);         // [3, 9, 2] — arr still [3, 1, 2]
arr.with(1, 99);                // [3, 99, 2] — replace index 1

// All 4 return NEW arrays without touching the original
console.log(arr); // [3, 1, 2] ✓
💡 Immutable operations are essential in React/Redux where you must not mutate state. Prefer [...arr].sort() or arr.toSorted() over arr.sort().

More Arrays Questions

EasyWhen would you use map vs forEach vs reduce vs filter?EasyHow do Array.find(), findIndex(), some(), and every() work?EasyHow do Array.flat() and Array.flatMap() work?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint