While debugging a javascript code that uses jQuery I found the following code:
[0, 0].sort(function()
{
baseHasDuplicate = false;
return 0;
});
By my understanding of javascript this code will sort array containing two zeroes with comparison function that will always set a global variable and will return equality, which has same effect as baseHasDuplicate = false;.
Coming from a valued source I think I missed something.
Did I miss something or is this a programming fail?
As you can see here (chinese), this code might be used to test for Chrome. EDIT: see below for the complete story..
As explained in the article, what happens is that Chrome optimizes the “.sort(…)” method in such a way that the
[0, 0].sort(...)call won’t execute the given comparison function.From the article, Chrome’s implementation of “.sort(…)” is something like:
As
0 === 0is true, it won’t callcomparefn.In the case of jQuery, it won’t set the global variable
baseHasDuplicatetofalse.EDIT: if you browse Sizzle’s source code, here for example (go to the yellow section under “Sizzle CSS Selector Engine”, called “Sizzle variables”), you will find the following explanation:
Looks demystified!