Immutable Array Methods: toSorted, toReversed, toSpliced and with
sort(), reverse() and splice() change the original array. That causes subtle bugs, especially with React state, where you must not mutate. ES2023 added non-mutating versions.
The old trap
const scores = [30, 10, 20];
const ranked = scores.sort((a, b) => b - a);
console.log(scores); // [30, 20, 10] - the original changed too!
The new methods
const scores = [30, 10, 20];
scores.toSorted((a, b) => a - b); // [10, 20, 30]
scores.toReversed(); // [20, 10, 30]
scores.toSpliced(1, 1); // [30, 20] (remove 1 item at index 1)
scores.toSpliced(1, 0, 15); // [30, 15, 10, 20] (insert)
scores.with(0, 99); // [99, 10, 20] (replace index 0)
console.log(scores); // [30, 10, 20] - untouched
React state updates become simpler
// Sort a list for display without mutating state
const visible = todos.toSorted((a, b) => a.dueDate - b.dueDate);
// Update one item
setTodos((todos) => todos.with(index, { ...todos[index], done: true }));
// Remove one item
setTodos((todos) => todos.toSpliced(index, 1));
// Move an item up
setTodos((t) => t.toSpliced(i, 1).toSpliced(i - 1, 0, t[i]));
Things to know
- They make shallow copies: objects inside the array are shared, not cloned.
with()throws aRangeErrorfor an out-of-range index instead of growing the array.- They also exist on typed arrays (except
toSpliced). - Supported in all modern browsers and current Node.js versions.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.