JavaScript · The language round
Why does array sort behave unexpectedly with numbers?
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.
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
ashould come beforeb - Return a positive number when
ashould come afterb - 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.
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]Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does `[10, 2, 1].sort()` not sort numerically?
- 2What does a comparator need to return?
- 3Does `sort` mutate the original array?
- 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.