What does console.log([1, 5, 10, 2, 25].sort()) output?
A past puzzle — fully playable. 4 attempts, hints on wrong guesses.
stdle-50.js
1console.log([1,5,10,2,25].sort())
Coercion
Answer & explanation
Console output
[ 1, 10, 2, 25, 5 ]
Why
Array.prototype.sort with no comparator converts each element to a string and sorts by UTF-16 code unit order. Lexicographically, "10" precedes "2" because "1" comes before "2". To sort numbers correctly you must pass a comparator: sort((a, b) => a - b). This default trips up nearly every JS developer at least once.