← Back to JavaScript, page 2

javascript-0035 · Medium mid

Why does [10, 9, 1].sort() return [1, 10, 9]? How does Array.prototype.sort work and what are its pitfalls?

Without a comparator, sort converts items to strings and compares them in UTF-16 order, so 10 comes before 9. A comparator function returning a negative, zero, or positive number gives numeric or custom ordering. sort changes the array in place, is stable in modern engines, and needs localeCompare or Intl.Collator for human-friendly text order.

Full answer

The default order of sort() is text order. Every item is converted to a string, and strings are compared character by character using UTF-16 code unit values. The string "10" starts with "1", which comes before "9", so 10 lands before 9. Items that are undefined are always placed at the end without calling the comparator.

To sort numbers, pass a comparator: (a, b) => a - b for ascending, (a, b) => b - a for descending. The comparator returns a negative number if a goes first, a positive number if b goes first, and zero if they are equal. Returning a boolean such as a > b is a bug, because true and false become 1 and 0 and never negative.

sort mutates the array and returns the same array. Copy first with [...list].sort(...), or use toSorted (ES2023), which returns a new array. Since ES2019, sort must be stable, so items that compare equal keep their original relative order. This makes it safe to sort by several keys in separate passes, from the least important key to the most important.

For text shown to people, plain code unit order puts uppercase letters before lowercase ones and accented letters after z. Use a.localeCompare(b) or new Intl.Collator('en').compare instead. For large lists, a collator object is faster because it is created once.

A comparator must be consistent. Random comparators such as () => Math.random() - 0.5 produce a biased shuffle.

javascript
console.log([10, 9, 1].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
console.log([10, 9, 1].sort((a, b) => b - a));
console.log([3, 1, 2].sort((a, b) => a > b)); // boolean comparator: wrong, see the notes
console.log([3, undefined, 1].sort((a, b) => a - b));

const names = ['zara', 'Anil', 'émile', 'Bina', 'emma'];
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b, 'en')));
console.log([...names].sort(new Intl.Collator('en', { sensitivity: 'base' }).compare));

const students = [
  { name: 'Asha', grade: 'B' },
  { name: 'Ravi', grade: 'A' },
  { name: 'Meera', grade: 'B' },
  { name: 'Dev', grade: 'A' },
];
const byGrade = students.toSorted((x, y) => x.grade.localeCompare(y.grade));
console.log(byGrade.map((s) => s.name).join(', '));
console.log(students.map((s) => s.name).join(', '));

const list = [2, 1];
const sorted = list.sort();
console.log(sorted === list, list);

Run with Node.js v24.22.1 as js-35.js; two runs gave identical output. Output: [ 1, 10, 9 ] [ 1, 9, 10 ] [ 10, 9, 1 ] [ 3, 1, 2 ] [ 1, 3, undefined ] [ 'Anil', 'Bina', 'emma', 'zara', 'émile' ] [ 'Anil', 'Bina', 'émile', 'emma', 'zara' ] [ 'Anil', 'Bina', 'émile', 'emma', 'zara' ] Ravi, Dev, Asha, Meera Asha, Ravi, Meera, Dev true [ 1, 2 ]

Key points

  • Default sort compares strings in UTF-16 order, so numbers sort wrongly.
  • Use a comparator returning negative, zero, or positive; do not return a boolean.
  • sort mutates the array; use toSorted or copy first.
  • Sort is stable in modern engines.
  • Use localeCompare or Intl.Collator for human-readable text.

Common mistakes

  • Sorting numbers without a comparator.
  • Returning a boolean from the comparator.
  • Sorting an array that is part of shared state and mutating it by accident.
  • Using a - b with values that can be undefined, NaN, or strings; the result may be NaN, which is inconsistent.

Follow-ups

  • How would you sort objects by two keys, for example grade and then name?
  • What does a stable sort mean, and why did it matter in the specification change?
  • Why does the "random comparator" shuffle give a biased result?

Tips

  • Explain the string conversion first; it answers the question in one step.
  • Mention the mutation and stability points without being asked.
  • Recommend localeCompare for names. It shows you think about international users.