Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How's JavaScript's native sort function implemented?

Let's see an example first.

var everything = [4,'Red', '$200', 'white', 7.4, 12, true, 0.3, false];
console.log(everything.sort(function(a, b) {return a - b;})); 
// [4, "Red", "$200", "white", false, 0.3, true, 7.4, 12]

I think this is weird, even when I know Number("Red"), Number("$200") and Number("white") all give NaN when comparing.

Why is 4 at the first of the result? I guess it has something to do with the implementation of Array.prototype.sort, so how can I see its implementation?

like image 521
Ovilia Avatar asked Nov 02 '13 05:11

Ovilia


Video Answer


1 Answers

Specification

According to ECMAScript 5 - Section 15.4.4.11,

If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the behaviour of sort is implementation-defined.

[...]

A function comparefn is a consistent comparison function for a set of values S if all of the requirements below are met for all values a, b, and c (possibly the same value) in the set S [...]

  • Calling comparefn(a,b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number, and v is not NaN. [...]

That is to say, if the return value of the comparison function is NaN, then the behaviour of the call to sort is 'implementation defined'.


In practice

Google Chrome and NodeJS (V8 Engine), as well as Opera (Futhark/Carakan) return:

[4, "Red", "$200", "white", false, 0.3, true, 7.4, 12]

Firefox (SpiderMonkey) returns:

[false, 0.3, true, 4, "Red", "$200", "white", 7.4, 12]

Internet Explorer returns:

["Red", "$200", false, 0.3, true, 4, "white", 7.4, 12]
like image 160
azz Avatar answered Sep 25 '22 01:09

azz