Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does [33, 2, 8].sort() not sort numbers correctly?

Do you know what will be the output of this code?

JavaScript
const numbers = [33, 2, 8]; 
numbers.sort();
console.log(numbers[1])
Show answer and explanation

This returns 33, but why is that?

JavaScript is a dynamically typed language, which means that all standard library functionality must, at some point, decide how to work for most, if not all, use-cases.

Always keep in mind that the following array is valid:

const array = ["1", true, 55, 1.421, "foo", {}];

Array.prototype.sort now needs to make a decision on how to handle such scenarios, and the solution is pretty straight-forward:

Convert all values to their string representation (because every value in JavaScript can always be converted to a string!), and then sort them in lexicographic order.

Which basically makes sort see the array as this:

const intermediate = ["33", "2", "8"];

And in lexicographic order, no matter how many characters a string has, comparison starts at position 0, and "3" comes before "8".

And in the end, the result is this:

["2", "33", "8"];
Take the full quiz Next question →

More Arrays questions

  1. What happens when you assign past the end of a JavaScript array?
  2. Why does [1, 2, 3].map(parseInt) return [1, NaN, NaN]?
  3. What does Array.push() return in JavaScript?
  4. How do you remove duplicates from an array with Set?
  5. What does Array.from({ length: 3 }) create?

Related topics