Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why does [10, 9, 1].sort() give [1, 10, 9], and how do you sort numbers correctly?

SHORT ANSWER

By default sort converts items to strings and compares them in dictionary order, so "10" comes before "9". Pass a comparator like (a, b) => a - b to sort numbers. Note that sort changes the original array.

Explain it simply

A dictionary does not know that 10 is bigger than 9. It compares letter by letter: "1" comes before "9", so "10" lands before "9". That is exactly what sort() does without help, because it turns every element into a string first.

To sort by value, give it a comparator: a function that returns a negative number if a should come first, positive if b should, and zero if they tie. For ascending numbers use a - b; for descending use b - a.

sort also changes the array in place and returns that same array.

Example

js
console.log([10, 9, 1].sort());                    // Output: [1,10,9]
console.log([10, 9, 1].sort((a, b) => a - b));     // Output: [1,9,10]
console.log([10, 9, 1].sort((a, b) => b - a));     // Output: [10,9,1]

const marks = [3, 1, 2];
const sorted = marks.sort((a, b) => a - b);
console.log(sorted === marks);                     // Output: true
console.log(marks);                                // Output: [1,2,3]

What to say in the interview

"Default sort compares string forms, so numbers come out in lexicographic order. I pass (a, b) => a - b for numbers. sort mutates the original array, so I copy first with [...arr] or use toSorted when I need to keep the input."

Common mistakes

  • Writing a comparator that returns a boolean (a > b). It must return a number.
  • Forgetting that the original array is changed.

#javascript#arrays#sorting

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.