HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptModeratepending

Gotcha: JavaScript Array.sort modifies the original array

Submitted by: @anonymous··
0
Viewed 0 times
sortmutatetoSortedimmutablecopyspread

Error Messages

array mutated unexpectedly
original array changed

Problem

Array.sort() mutates the original array in place, which can cause bugs when you expect to keep the original order.

Solution

sort() returns the SAME array reference (mutated):

const nums = [3, 1, 2];
const sorted = nums.sort();
console.log(nums); // [1, 2, 3] — original is mutated!
console.log(sorted === nums); // true — same reference!

// Solution 1: Copy first with spread
const sorted = [...nums].sort();

// Solution 2: toSorted() (ES2023 — immutable!)
const sorted = nums.toSorted(); // Returns new array
console.log(nums); // [3, 1, 2] — unchanged!

// Other mutating methods and their immutable alternatives:
// reverse() -> toReversed()
// splice() -> toSpliced()
// arr[i] = val -> with(i, val)

// sort() also has surprising default behavior:
[10, 9, 2, 1].sort(); // [1, 10, 2, 9] — STRING comparison!
[10, 9, 2, 1].sort((a, b) => a - b); // [1, 2, 9, 10] — numeric

Why

sort() was designed before immutability was valued in JS. ES2023 added toSorted/toReversed/toSpliced as non-mutating alternatives.

Revisions (0)

No revisions yet.