News for hackers. Stuff that matters.
Re:The Curious Case of JavaScript’s `sort` by bilalq on Wednesday April 13, 2016 @11:00AM (#11488719)
No, this has nothing to do with how "JS sorts numbers". JavaScript sorts arrays by using a default comparator that runs .toString and compares unicode code point values (with safe handling around null/undefined).

There is no concept of a typed number array in JS. There is just "Array", and an array's contents can be heterogenous.

Imagine the following:

    ['a', 'c', 'b'].sort() // ['a','b','c']
    ['a', 1].sort() // [1, 'a']
    [1, ['foo'], {bar: 'baz'}, 'a', '2', null, undefined].sort() // [1, '2', {bar:'baz'}, 'a', ['foo'], null, undefined]

The default comparator is one that can be run on any arbitrary array. It's up to you as a caller to specify that you'd like to sort by a different comparator.

For a more detailed read, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:The Curious Case of JavaScript’s `sort` by tzs on Wednesday April 13, 2016 @02:03PM (#11490622)
> JavaScript sorts arrays by using a default comparator that runs .toString and compares unicode code point values (with safe handling around null/undefined).

Is there an explanation somewhere of how they decided on that as the default comparator? My first inclination would have been to use "<" as the default comparator. That would sort purely numeric arrays numerically, and purely string arrays lexically, leaving only the case of arrays that mix numerical and non-numerical elements needing the programmer to step in and give an explicit comparator.

Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @11:18AM (#11488892)
> There is no concept of a typed number array in JS

Note that nowadays there are indeed Int16Array, Float32Array, and so forth, and their sort methods work numerically like you'd expect.

Re:The Curious Case of JavaScript’s `sort` by abc_lisper on Wednesday April 13, 2016 @11:15AM (#11488859)
One of the many reasons why I keep away from JS - it deviates from the norm without good reason, in arbitrary places.
Re:The Curious Case of JavaScript’s `sort` by zaphar on Wednesday April 13, 2016 @11:39AM (#11489099)
And this kids is an example of a problem that compile time type checking can help with.
Re:The Curious Case of JavaScript’s `sort` by toupeira on Wednesday April 13, 2016 @01:45PM (#11490409)
Or simply strong typing.