isNaN is not equal Number.isNaN
- Published at
- Updated at
- Reading time
- 1min
I read Exploring ES6 by Axel Rauschmayer to learn tiny details about JavaScript. I can't recommend the book enough!
ES6 is not new anymore. Everybody talked/talks about the new shiny features. Often overlooked are new methods like method Number
.
So, what's the deal with this new method? We already had the global function isNaN
, didn't we?
Let's take a step back... How do you figure out if a value is NaN
when the global isNaN
method isn't of big help?
isNaN('foo'); // true
isNaN({}); // true
isNaN(NaN); // true
isNaN(12); // false
Unfortunately, the global isNaN
comes with many false positives. That's why everybody used the strict equality check.
function myOwnIsNaN(value) {
return value !== value;
}
That works because NaN
is not equal to itself.
The new static method Number
fixes the odd global behavior and works as expected.
Number.isNaN('foo'); // false
Number.isNaN(12); // false
Number.isNaN({}); // false
Number.isNaN(NaN); // true ๐
I like that!
Join 5.4k readers and learn something new every week with Web Weekly.