Understanding isNaN Underscore

Adapted from underscore.js source:

_.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; 

Why would they do that? Is the above implementation equivalent:

 _.isNaN = function(obj) { return obj !== obj; }; 

If so, why the “more complex" version? If not, what are the differences in behavior?

+7
source share
4 answers

_.isNaN(new Number(NaN)) returns true.

And what about the design .

 var n = new Number(NaN); console.log(_.isNaN(n), n!==n); // logs true, false 
+4
source

In a host environment (for example, a web browser environment), other values ​​may be entered that are not equal to themselves. The _.isNumber(obj) ensures that the input is a numeric value, so _.isNaN only returns true if NaN passed.

+1
source

If the + value is set before any value without the previous value to +, the JavaScript engine will try to convert this variable to Number.If it is valid, it will give you an else number to which it will return NaN. for example

  + "1" // is equal to integer value 1 + "a1" // will be NaN because "a1" is not a valid number 

In the case above

  +"a1" != "a1" // true, so this is not a number, one case is satisfied +"1" == "1" // true, so it is number 

Another simple case: why the expression below gives this conclusion

  console.log("Why I am " + typeof + ""); // returns "Why I am number" 

Because + "" is 0.

If you want to check if this is a number or not, you can use the following function

 function isNumber(a){ /* first method : */ return (+a == a); /* second method : */ return (+(+a) >= 0); // And so many other exists } 

Someone will correct me if I'm wrong somewhere.

0
source

I found one case for _.isNaN It shows a different result with a native one if you pass an object there

 _.isNaN({}) => false //but isNaN({}) => true 
0
source

All Articles