JavaScript · The language round

Why does array sort behave unexpectedly with numbers?

MediumarrayssortcomparatorsUpdated Oct 2026
Quiz this track

Short answer

sort converts elements to strings by default, so numbers are compared lexicographically. It also mutates the array. Pass a comparator for numeric or custom ordering.

The default comparison is string-based, which is why [10, 2, 1].sort() produces [1, 10, 2]. This is one of the most common JavaScript surprises.

js
console.log([10, 2, 1].sort()); // [1, 10, 2]

console.log([10, 2, 1].sort((a, b) => a - b)); // [1, 2, 10]
console.log([10, 2, 1].sort((a, b) => b - a)); // [10, 2, 1]

How the comparator works

  • Return a negative number when a should come before b
  • Return a positive number when a should come after b
  • Return zero when the order does not matter
  • The comparator must be consistent or the sort order is undefined

sort mutates the array and returns the same reference. If you need a new array, copy first with slice() or spread, or use the newer toSorted() method.

js
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);

console.log(sorted); // [1, 2, 3]
console.log(original); // [3, 1, 2]
Modern engines use a stable sort, so equal elements keep their relative order. Do not rely on stability for correctness unless the comparator actually returns zero for ties.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why does `[10, 2, 1].sort()` not sort numerically?
  2. 2What does a comparator need to return?
  3. 3Does `sort` mutate the original array?
  4. 4How do you sort objects by a property?

Say it in the interview

By default sort converts elements to strings and compares them lexicographically, so ten comes before two. For numbers I pass a comparator that subtracts b from a. The comparator returns negative, positive or zero to describe the desired order. sort mutates the array, so I copy first or use toSorted when I need immutability.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.