News for hackers. Stuff that matters.
Re:The Curious Case of JavaScript’s `sort` by witty_username on Wednesday April 13, 2016 @10:45AM (#11488602)
So if I'm understanding correctly, JS sort sorts numbers by their string value? That's crazy. And it seems you have to add a compare function just to do a basic operation to sort numbers.
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.
Re:The Curious Case of JavaScript’s `sort` by zeveb on Wednesday April 13, 2016 @12:27PM (#11489627)
> So if I'm understanding correctly, JS sort sorts numbers by their string value? That's crazy.

It's JavaScript … it doesn't have to be sane; we'll use it anyway.

I think that Erlang had the most elegant solution: it defines a total order over all objects (number < atom < reference < fun < port < pid < tuple < list < bit string). Of course, Erlang's 'strings' are pretty inelegant (they're just lists of integers, which are printed as strings if they happen to incidentally be valid characters), so I guess there's some Law of Conservation of Bogosity at play here.

Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @11:09AM (#11488795)
Array#sort sorts all elements by their converted string value.

It may seem like a strange way to spec the language, but I'm not sure what would have been better. It wouldn't make sense for sort to have to run through the array checking types before it starts, or for it to dynamically change what kind of comparison it does depending on the types of each pair of elements being compared.

Re:The Curious Case of JavaScript’s `sort` by xlm1717 on Wednesday April 13, 2016 @11:20AM (#11488915)
It might have made more sense to not have default behavior and force the user to specify how they want to sort. They could also have done what PHP did and provided several different .sort functions depending on how you want to sort.
Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @11:33AM (#11489045)
I think ECMA4 proposed behavior flags, so you could do:

    arr1.sort( Array.NUMERICAL | Array.DESCENDING )
    arr2.sort( Array.CASE_INSENSITIVE )
or similar.
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @11:45AM (#11489173)
What would make sense (and what most other languages seem to do) is compare elementwise, using whatever ordering javascript would usually use. Therefore [X] < [Y] would be true whenever X<Y is true (for example)
Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @12:17PM (#11489532)
That would have undesirable side effects - e.g. it would mean the results of the sort are not necessarily specified. If the array contains NaN, for example, calling a sort like that would have different results depending on the order in which the elements are compared, which would likely vary by JS engine.
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @12:20PM (#11489559)
I don't really understand your problem -- this is how array comparison is implemented in C++, Python, Ruby, Java (when using the default isComparable on most array-list types) and Haskell (from the languages I use frequently). Javascript is the only weird outlier.
Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @12:45PM (#11489846)
I don't know what you're taking issue with. The results of sorting in JS with a simple (a<b) comparison will necessarily vary by JS implementation, and I'm suggesting that would be a drawback for a default specified behavior.

E.g.:

    [1,3,NaN,2,5].sort( (a,b) => a<b ? -1 : 1 )
    // Chrome:  [ NaN, 1, 2, 3, 5 ]
    // Firefox: [ 2, 5, NaN, 1, 3 ]
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @01:16PM (#11490145)
I am refering to this:

In (almost) every other language ever the following is true. In Javascript it is false.

    [2] < [11]
This means:

[[2], [11]].sort() // Javascript: [ [11], [2] ]

Re:The Curious Case of JavaScript’s `sort` by fenomas on Wednesday April 13, 2016 @02:02PM (#11490615)
You're overlapping a couple of separate things. The article and my initial comment were about sorting arrays of numbers. If you're sorting arrays of arrays, the behavior of ([2] < [11]) is slightly beside the point, since Array.sort() doesn't compare the arrays, it converts all elements to strings first.

As for the actual behavior of ([2] < [11]), the issue there is that "Array" is not a type in JS, arrays are just objects that happen to have properties called "0" and "1" and so on. Hence operators don't have any special cases for arrays, so getting comparisons to work like you had hoped would mean the comparison operator would need weird special rules where, whenever it's passed two objects it checks if they both have properties called "0", and if so do one thing, if not do something else, etc.

Re:The Curious Case of JavaScript’s `sort` by gpvos on Wednesday April 13, 2016 @03:41PM (#11491515)
That still wouldn't specify how to sort [ 1, [ 5 ], "hi", { a: 5 }, new Date(), /test/ ] , and which way to sort that would "make sense" anyway? Better to specify something simple but incomplete than something complicated that will still necessarily be either incomplete or useless or both.
Re:The Curious Case of JavaScript’s `sort` by pjc50 on Wednesday April 13, 2016 @10:53AM (#11488658)
This is what happens when people try do to arithmetic in a typeless language. Javascript does not really have a number type; it just has values. Sometimes it infers that you want to do arithmetic on them.

What is the correct order of the items ["2", 10, "banana", [[]], "", 1]?

See also https://www.destroyallsoftware.com/talks/wat

Bonus: sometimes you can get the same kind of behaviour in Excel when importing CSV.

Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @10:59AM (#11488709)
The language isn't typeless. Other language (python and ruby, among many others) manage to integer and string comparision correct.

It is trickier when someone compares "2" and 3, should we say it's invalid (my preference) or turn 2 into an integer, or 3 into a string? However, there is NO reason for there to be an issue comparing 1 and 11. This is just an unfortunately mistake that is too deeply baked into the language to fix at this point.

Re:The Curious Case of JavaScript’s `sort` by xlm1717 on Wednesday April 13, 2016 @11:08AM (#11488787)
Where is the issue comparing 1 and 11? 1 < 11 still returns true. [11,1].sort((a,b) => a -b) still returns [1, 11].
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @11:14AM (#11488848)
Sorry, 1 and 11 isn't a problem in javascript. Insert two troublesome numbers :)
Re:The Curious Case of JavaScript’s `sort` by evan_ on Wednesday April 13, 2016 @11:24AM (#11488955)
Seems like it should be up to you to come up with the troublesome numbers, since you're the one making claims.
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @11:34AM (#11489055)
Oh sorry, here we go.

    > [2] < [11]
    false
Technically, a combination of integers and arrays. Still took me an afternoon to track down (it didn't occur to me javascript would work like that).
Re:The Curious Case of JavaScript’s `sort` by gpvos on Wednesday April 13, 2016 @03:45PM (#11491547)
Then your knowledge of Javascript is sorely lacking. To make arrays work like that in Javascript would be very complicated, and counterintuitive to those who know how Javascript arrays work.
Re:The Curious Case of JavaScript’s `sort` by CJefferson on Wednesday April 13, 2016 @04:10PM (#11491765)
I agree my knowledge of JavaScript is lacking, I just (wrongly) assumed arrays would act similarly to other languages.

Obviously it's too late to change JavaScript now, but Iwould be interested to know why it would have been complicated to do this differently originally, and why it would be countintuitive? Is there anything I can read about this kind of thing?

Re:The Curious Case of JavaScript’s `sort` by gpvos on Wednesday April 13, 2016 @05:13PM (#11492265)
Yeah, that's more or less what you get when you hack a language together in 10 days... Arrays in JS are just a special case of objects, which are just name-value hashmaps. Although they usually have some optimizations in their internal implementation.

I guess "Javascript: the Good Parts" is as good a place to start as any. It doesn't really go into the design decisions though.

Re:The Curious Case of JavaScript’s `sort` by xlm1717 on Wednesday April 13, 2016 @11:07AM (#11488771)
It's not that it sometimes infers what you want to do. It's that it has defaults and if you want to do something besides the default, you need to specify what it is you want to do.