isNaN is not equal Number.isNaN
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
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!
Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 5 days ago.
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 5 days ago.