0
Challenge · 16Just Enough JavaScript

Sorting and the comparator

JavaScriptused in ~100% of apps

This is the single most reliable way to lose marks in JavaScript. Sort a list of numbers the obvious way and you get an answer that is confidently, silently wrong. It has caught nearly every JavaScript programmer alive at least once.

Core idea. sort() with no arguments turns everything into text and sorts alphabetically, so 10 comes before 5. For numbers you must always pass a comparator: (a, b) => a - b. And sort changes the original array rather than returning a new one.
Playground, this isn't a screenshot
[10, 5, 40, 25, 1000, 1]. Verified by running it
.sort(). Sorts as text
1
10
1000
25
40
5

Wrong, and no error at all.

.sort((a, b) => a - b)
1
5
10
25
40
1000

Correct.

Both ran without complaint. Only one is right, and nothing tells you which.

↑ play a little first, then dig in