gotchaModeratepending
Array.sort mutates the original array in JavaScript
Viewed 0 times
sort mutatestoSortedspreadimmutable sortin-place
browsernodejs
Error Messages
Problem
Array.sort() modifies the original array in place, unlike most array methods that return new arrays. Sorting a prop or state array directly causes bugs.
Solution
Always spread before sorting: [...arr].sort() or use Array.toSorted() (ES2023+). Same for reverse(): use toReversed(). Same for splice(): use toSpliced().
Why
sort() was designed to mutate for performance reasons in early JavaScript. The new non-mutating alternatives (toSorted, toReversed, toSpliced) were added in ES2023.
Code Snippets
Non-mutating sort patterns
const original = [3, 1, 2];
// WRONG: mutates original
const sorted = original.sort();
console.log(original); // [1, 2, 3] -- mutated!
// RIGHT: spread first
const sorted = [...original].sort();
console.log(original); // [3, 1, 2] -- safe
// RIGHT: toSorted (ES2023)
const sorted = original.toSorted();
const reversed = original.toReversed();
const without = original.toSpliced(1, 1); // remove index 1Revisions (0)
No revisions yet.