What does this (useless?) Javascript code do?

When debugging javascript code using jQuery, I found the following code:

[0, 0].sort(function() { baseHasDuplicate = false; return 0; }); 

In my understanding of javascript, this code will sort an array containing two zeros with a comparison function that will always set a global variable and will return an equality that has the same effect as baseHasDuplicate = false; .
Based on a valuable source, I think I missed something. Am I missing something or is it a programming failure?

+7
javascript jquery
source share
1 answer

As you can see here (Chinese), this code can be used to test Chrome. EDIT: see below for the full story .

As explained in the article, what happens is that Chrome optimizes the ".sort (...)" method so that calling [0, 0].sort(...) will not perform this comparison function.

From the article, a Chrome implementation in .sort (...) format looks something like this:

 function sort(comparefn) { var custom_compare = (typeof(comparefn) === 'function'); function Compare(x,y) { if (x === y) return 0; if (custom_compare) { return comparefn.call(null, x, y); } ... } 

Since 0 === 0 true, it will not call comparefn .

In the case of jQuery, the global variable baseHasDuplicate will not be set to false .


EDIT : if you are viewing the Sizzle source code, here (go to the yellow section under the heading "Sizzle CSS Selector Engine" called "Sizzle variables"), you will find the following explanation:

 var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); 

It looks demystified!

+12
source share

All Articles