What is sort()?

sort(compareFn?) sorts an array in place and returns the same array; without a compare function it converts items to strings and sorts them by UTF-16 code units, which gives wrong results for numbers.

The default-sort trap

[10, 9, 1, 100].sort() gives [1, 10, 100, 9] because "10" < "9" as strings. Always pass a compare function for numbers.

Compare functions

(a, b) => result:

  • negative: a comes first
  • positive: b comes first
  • 0: keep their relative order

Patterns:

  • Numbers ascending: (a, b) => a - b; descending: (a, b) => b - a.
  • Strings, human-friendly: (a, b) => a.localeCompare(b), which handles accents and case. Pass options like { numeric: true } to sort "file2" before "file10".
  • By several keys: compare the first key, and fall back to the next when it is 0 (a.last.localeCompare(b.last) || a.age - b.age).

Stability

Since ES2019, sort is stable: items that compare equal keep their original order. That makes multi-pass sorting reliable.

Mutation

sort changes the original array, which causes bugs with React state or shared data. Use toSorted(compareFn) (ES2023) to get a sorted copy, or [...arr].sort(...).

Performance

Engines use TimSort, O(n log n). For huge data or heavy compare functions, pre-compute sort keys once.

Code example

js
1const nums = [10, 9, 1, 100, 25];
2console.log([...nums].sort()); // [1, 10, 100, 25, 9] <- string order!
3console.log([...nums].sort((a, b) => a - b)); // [1, 9, 10, 25, 100]
4console.log(nums.toSorted((a, b) => b - a), nums); // sorted copy, original untouched
5
6// Human-friendly string sorting
7const files = ["file10.txt", "File2.txt", "file1.txt", "éclair.txt"];
8console.log(files.toSorted((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" })));
9// ["éclair.txt", "file1.txt", "File2.txt", "file10.txt"]
10
11// Multi-key sort: by role, then by age (stable sort keeps ties in order)
12const people = [
13 { name: "Ada", role: "dev", age: 36 },
14 { name: "Linus", role: "admin", age: 28 },
15 { name: "Grace", role: "dev", age: 30 },
16];
17const sorted = people.toSorted((a, b) => a.role.localeCompare(b.role) || a.age - b.age);
18console.log(sorted.map((p) => `${p.role}:${p.name}`)); // ["admin:Linus", "dev:Grace", "dev:Ada"]
19
20// sort returns the SAME array (mutation)
21const arr = [3, 1, 2];
22console.log(arr.sort() === arr); // true

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app