isNaN is not equal Number.isNaN

1 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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.isNaN 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.isNaN 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!

Load time