Why Numbers Sort Incorrectly Without a Comparator
You'll learn why [10, 2, 5].sort() produces the surprising result [10, 2, 5] instead of [2, 5, 10].
The Default Sort Behavior You Already Know
You've seen that sort() arranges array elements using its default behavior. But here's the catch: JavaScript converts every element to a string before comparing them.
The String Conversion Problem
When you call sort() without a comparator function, JavaScript:
- Converts each element to a string
- Compares those strings character-by-character using Unicode values
So [10, 2, 5].sort() actually compares "10", "2", and "5".
In string comparison:
"10"starts with"1""2"starts with"2""5"starts with"5"
Since "1" comes before "2" and "5" alphabetically, you get [10, 2, 5] — sorted alphabetically, not numerically!
Why This Happens
Think of it like sorting words in a dictionary. The word "apple" comes before "banana" because "a" comes before "b". Similarly, "10" comes before "2" because the first character "1" comes before "2".
[10, 2, 5].sort(); // [10, 2, 5] ❌ Unexpected!
[100, 21, 3].sort(); // [100, 21, 3] ❌ Still wrong!
['10', '2', '5'].sort(); // ['10', '2', '5'] — same result
All three examples produce the same ordering because everything becomes a string internally.
The Solution Preview
This is exactly why you learned about comparator functions in the previous lesson — they let you define custom comparison logic that treats numbers as numbers, not strings.
Key Takeaway: Without a comparator, sort() converts all elements to strings and compares them alphabetically, which produces incorrect results for numeric arrays.