Unit 5 · Data and algorithms
Why JavaScript sort puts 10 before 9
With no compare function, .sort() turns every value into text and sorts like a dictionary, so “10” comes before “9”. Pass a compare function: .sort((a, b) => a - b) for smallest first.
The mix-up
What people often think
“.sort() with nothing inside sorts numbers by size.”
What the tutor says
Plain .sort() turns values into text and sorts them like dictionary words, so 10 comes before 9. Pass (a, b) => a - b.
How it works
In a dictionary, “19” comes before “3” because 1 comes before 3. That is exactly what plain .sort() does with numbers.
The compare function sets the direction. a - b sorts smallest first; b - a sorts largest first. Reversing a text-sorted list does not fix it: it is still compared as text, just backwards.
Side by side
[100, 9, 25, 1, 10].sort();
// [1, 10, 100, 25, 9][100, 9, 25, 1, 10].sort((a, b) => a - b);
// [1, 9, 10, 25, 100]Close cousins of this mix-up
The tutor watches for these in the same lesson.
“b - a and a - b do the same thing.”
The compare function decides the direction. b - a sorts from largest to smallest; a - b sorts smallest first.
“Reversing the list will put it right.”
Reversing text order gives 9, 25, 100, 10, 1, still wrong. The problem is comparing as text, not the direction.
“.sort() puts numbers in number order.”
Plain .sort() compares numbers as text, so 19 lands before 3. Use .sort((a, b) => a - b) to sort by value.
Practise it with a tutor watching
Sorting
Sort by hand with bubble and insertion sort, and sort numbers correctly in code.
Free with an account. The first two units need no account.