⚡ The Sort That Rearranged the Wrong Array
Array.prototype.sort() sorts the array in place and returns a reference to that same array – it does not hand back a new, independently sorted copy. Code that writes const sorted = items.sort(…) while still holding onto items elsewhere, expecting items to keep its original order, is actually mutating items itself; sorted and items are the exact same array object afterward, and anything else in the program that already had a reference to items sees it reordered too.
🔎 The Problem
const scores = [42, 7, 93, 15];
const originalOrder = scores; // same reference, not a copy
function getLeaderboard(list) {
// Looks safe - returns a new "sorted" variable:
const sorted = list.sort((a, b) => b - a);
return sorted;
}
const leaderboard = getLeaderboard(scores);
console.log(leaderboard); // [93, 42, 15, 7]
console.log(scores); // [93, 42, 15, 7] <- mutated!
console.log(originalOrder); // [93, 42, 15, 7] <- "changed"
// too, because it was always
// the same array under a
// different name
✅ Fix: Sort a Copy When the Original Order Has to Survive
- Sort a copy when the original order needs to survive: […items].sort(…) or items.slice().sort(…) both create a new array first, leaving the original untouched by the in-place sort that follows.
- Use Array.prototype.toSorted() – the newer, non-mutating sibling of sort(), available in modern engines – when you can rely on it; it returns a new sorted array and leaves the original exactly as it was, with no spread or slice needed.
- Treat any array passed into a function as something you shouldn’t mutate by default unless the function’s name or docs say otherwise – a function called getLeaderboard or formatForDisplay reads like it should be read-only, and sort() silently breaks that assumption for every caller.
🚨 Why This Is Dangerous
- Everything downstream of the mutation keeps working – the array is still a perfectly valid array, just in a different order, so nothing throws and nothing logs an error; the bug only surfaces as some other part of the program that shares the same array now showing things in the wrong order.
- It’s one of the most commonly miscredited ‘pure’ methods in JavaScript precisely because its siblings map, filter, and slice all return new arrays – sort() (and reverse() and splice()) are the odd ones out that mutate in place, and muscle memory from the others leads straight into this.
sort() never promised you a new array – it promised you the same array, rearranged, and handed back to you as if that were a kindness.
