Sorting Numbers Wrong
luljs still worksSort a list of numbers and they come back in the wrong order.
In 2026: Still works, and it bites people constantly. Array.prototype.sort with no comparator converts every element to a string and sorts those, so "16" sorts before "2". You have to pass (a, b) => a - b to sort numbers as numbers.
Where it came from: The default comparator in Array.prototype.sort converts elements to strings before comparing them, as documented on MDN. MDN ↗
<script>
document.write("<p><code>[16, 8, 4, 2].sort()</code> is <b>" + JSON.stringify([16,8,4,2].sort()) + "</b></p>");
document.write("<p><code>[16, 8, 4, 2].sort((a,b)=>a-b)</code> is <b>" + JSON.stringify([16,8,4,2].sort(function(a,b){return a-b;})) + "</b></p>");
</script>