Javascript sucks at sorting integers

In general, I heart Javascript. It’s one of the most misunderstood languages, but it has definitely made a comeback in a big way, not just with sweet client-side frameworks like Prototype and jQuery, but also on the server-side with CouchDB, MongoDB and Node.js.

But in its current form (Javascript 1.5), it sucks at sorting integers:

js> [10,5,3].sort(); // should be [3, 5, 10]
[10, 3, 5]

Suck! It’s trying to sort the integers alphabetically, as if they were strings. Fortunately, you can override the default comparator:

js> [10,5,3].sort(function(a, b) { return a - b });
[3, 5, 10]

That works nicely, but you still need to know to do that with integers, violating the principle of least surprise.