Not a Number

Checking for `NaN` is a minefield

Checking NaN is tricky

First of all, it's simply not trivial to check it.

NaN === NaN // false

This is one of those headscratchers that are like that just because. Long story short, there's a spec for floating point numbers which determines that NaN values are never equal.

Then, for a long time we've had only the isNaN() method, which covers the above case, but it get you some unexpected results.

isNaN(NaN) // true
isNaN('foo') // true

That's confusing. To navigate around that issue, in the ES5 days, people usually did something like:

var isNaN = function(value) {
  var n = isNaN(value)
  return n !== n
}

Thankfully, since ES6 came around, we now have a new method within the Number prototype that works consistently across every case:

Number.isNaN('foo') // false
Number.isNaN(NaN) // true

Important to note, both isNaN and Number.isNaN are available, careful not to mix them up! 💥

References

Get every post in your inbox
  • No spam. Ever.
  • Unsubscribe anytime. Easily.