isNaN is not equal Number.isNaN
- Published at
- Updated at
- Reading time
- 1min
I was on vacation last week and was reading Exploring ES6 by Axel Rauschmayer. And I can not say it enough โ it is a great read and I constantly learn new tiny details about JavaScript. I highly recommend giving it a try!
ES6 is nothing new today anymore and everybody talked/talks about the new shiny features but there is way more like the new method Number
and other unimportant looking additions.
So what's the deal with this new method? We already had the global function isNaN
, or?
So, how do you usually figure out if a value is NaN
? Well it turns out it's harder than you think because the global function is not a big help...
isNaN('foo'); // true
isNaN({}); // true
isNaN(NaN); // true
isNaN(12); // false
Using the global isNaN
there are a lot of false positives and that's why I went with an equality check for years.
function myOwnIsNaN(value) {
return value !== value;
}
That works because NaN
is not equal to itself.
The new static method Number
fixes the odd behavior and actually works like you'd expect it.
Number.isNaN('foo'); // false
Number.isNaN(12); // false
Number.isNaN({}); // false
Number.isNaN(NaN); // true ๐
Great, I like that!
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 6 days ago.