DEV Community

Atila Fassina
Atila Fassina

Posted on • Originally published at on

Not a Number

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:

const isReallyNaN = value => {
  const 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! 💥


Top comments (0)