How to check something is identical to NaN?

In Javascript:

NaN === NaN; // false 

I tried to determine when isNaN(foo) not just equivalent to +foo "is" NaN . But I don’t know how to say if something is NaN , except for the use of isNaN , which says yes to many things, none of which === NaN.

So, I think the right way to do this is to circumvent other possibilities:

 typeof NaN === 'number' // true 

Therefore I think

 typeof(foo) === 'number' && isNaN(foo) 

Is closest to what I think. This makes sense because it makes sense that NaN will be the only number that is not a number or something. Is this right and is this the best way?

+4
source share
3 answers

Take advantage of this:

 foo !== foo 

This is equivalent to typeof foo === 'number' && isNaN(foo) , and this is what Underscore.js uses exactly NaN to validate, too .

+7
source

The reason NaN is not equal to itself is because two calculations can become NaN for various reasons. If you perform two calculations and compare the results, you do not want them to be equal if one of the values ​​is NaN or both of them.

The isNaN method works fine as long as you use it only by numeric values. This gives unintuitive results for many other types, so you just shouldn't use it on anything other than numbers.

+3
source

If you can use ECMAScript 6 , you are Object.is :

 return Object.is(foo, NaN); 

Object.is() determines whether two values ​​are the same. Two values ​​are the same if one of the following values ​​is true:
[...]

  • both NaN

MDN also offers Polyfill if Object.is is undefined (uses the same trick foo!==foo ):

 if (!Object.is) { Object.is = function(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } }; } 
0
source

Source: https://habr.com/ru/post/1488182/


All Articles