Strange code in jQuery sources: var! == var? x: y;

I recently found one strange line in jQuery sources (latest version 1.9.1, Sizzle package, line 129 funescape ):

 funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? // <--- LINE 129 escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; 

What is the reason for comparing high !== high ? Obviously, return escaped will never be executed. Or am I missing something?

Link: https://github.com/jquery/sizzle/blob/master/sizzle.js#L129

+48
javascript jquery
Feb 08 '13 at 11:59
source share
3 answers

In fact, this is written in the comment right above:

// NaN means non-coding

So, first you need to perform this comparison to handle the NaN event, as in JavaScript:

NaN === NaN returns false .

As pointed out by James Wiseman , it is also important to know why the developer used high !== high instead of isNaN(high) , which would be clearer.

This is definitely based on performance. This test shows that a !== a is twenty times faster than isNaN(a) .

zzzzBov also indicates that isNaN() can be overwritten, using !== also more portable.

Further information from Benjamin Gruenbaum :

It is also worth noting that NaN does not correspond to anything else, because well, and also it is not equal to anything else in a non-strict sense

And from Jan Dvořák :

Also note that {valueOf:function(){return{}}} does it yourself

+57
Feb 08 '13 at 12:12
source share
— -

The condition high !== high returns true when high NaN . I wonder why the jQuery guys didn't use the much clearer isNaN(high) function, but this was probably due to performance considerations, as coopah pointed out.

NaN ( N ot- a - N umber) means a result that cannot be represented as Number . This is an indefinite number.




Why does NaN === NaN return false?

Consider

 0/0 = NaN Math.asin(2) = NaN 

You know that 0/0 is different from Math.asin(2) , so why would NaN be equal to NaN ?

+13
Feb 08 '13 at 12:16
source share

I support some comments here, but I think this is decent information.

Some comments on the original question suggested that this validation method for NaN is actually much faster than isNaN()

When used in conjunction with the following parseInt alternative, parseFloat we have a very fast way to convert to a number and check its numeric state.

Is Subtracting Zero some kind of JavaScript performance trick?

So instead

 function Translated(val) { var x = parseFloat(val); if (!isNaN(x)) { alert("Not a number"); } } 

We can have

 function WTF(val) { var x = val - 0; if (x !== x) { alert("Not a number"); } } 
+6
Feb 08 '13 at 12:29
source share



All Articles