Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Why does [10, 9, 1].sort() return [1, 10, 9] in JavaScript?

SHORT ANSWER

By default sort converts elements to strings and compares them in dictionary order, so "10" comes before "9". Pass a comparator such as (a, b) => a - b to sort numbers numerically.

Explain it simply

Sorting words in a dictionary: "apple" comes before "banana" letter by letter. The default sort() treats every element like a word. Comparing the text "10" and "9", the first character "1" is smaller than "9", so "10" comes first.

A comparator function fixes this. It receives two values and returns a negative number if the first should go earlier, positive if later, and zero if equal. a - b does exactly that for numbers.

Example

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

Complexity

Sorting is O(n log n) time either way; copying the array first adds O(n) space.

What to say in the interview

"The default sort compares values as strings, so numbers sort lexicographically. I pass a comparator, a minus b for ascending or b minus a for descending. Also, sort mutates the original array, so I copy it first if I need the original order."

Common mistakes

  • Forgetting that sort changes the original array.
  • Writing a comparator that returns a boolean, such as a > b, which does not work correctly.

#sorting#javascript

Related questions

Practise more Data Structures & Algorithms questions

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

Open Data Structures & Algorithms 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.