gotchajavascriptMajor
Array.sort() mutates in place and sorts as strings by default
Viewed 0 times
toSorted() requires ES2023 / Node 20+
array sortsort mutatesstring sortnumeric sorttoSortedcompare function
Problem
Array.sort() modifies the original array AND sorts elements as strings by default. [10, 9, 2, 1].sort() returns [1, 10, 2, 9] because '10' comes before '2' alphabetically.
Solution
Always provide a compare function, and use toSorted() to avoid mutation:
const nums = [10, 9, 2, 1];
// BAD: sorts as strings, mutates original
nums.sort(); // [1, 10, 2, 9]
// GOOD: numeric sort
nums.sort((a, b) => a - b); // [1, 2, 9, 10]
// BEST: non-mutating (ES2023)
const sorted = nums.toSorted((a, b) => a - b); // nums unchanged
// String sort (case-insensitive)
names.sort((a, b) => a.localeCompare(b));
// Sort by object property
users.sort((a, b) => a.age - b.age);
const nums = [10, 9, 2, 1];
// BAD: sorts as strings, mutates original
nums.sort(); // [1, 10, 2, 9]
// GOOD: numeric sort
nums.sort((a, b) => a - b); // [1, 2, 9, 10]
// BEST: non-mutating (ES2023)
const sorted = nums.toSorted((a, b) => a - b); // nums unchanged
// String sort (case-insensitive)
names.sort((a, b) => a.localeCompare(b));
// Sort by object property
users.sort((a, b) => a.age - b.age);
Why
JavaScript's sort() converts elements to strings and compares their UTF-16 code unit sequences. This is useful for string arrays but completely wrong for numbers. The mutation is also surprising — most array methods (map, filter) return new arrays.
Gotchas
- toSorted() is ES2023 — check browser/Node support
- sort() is not stable in all engines before ES2019
- The compare function should return negative, zero, or positive — not boolean
- reverse() also mutates — use toReversed() for non-mutating
Code Snippets
Proper array sorting
// String sort (default)
[10, 9, 2].sort() // [10, 2, 9] — WRONG for numbers!
// Numeric sort
[10, 9, 2].sort((a, b) => a - b) // [2, 9, 10]
// Non-mutating (ES2023)
[10, 9, 2].toSorted((a, b) => a - b) // [2, 9, 10]Context
When sorting arrays in JavaScript, especially numbers
Revisions (0)
No revisions yet.