DEV Community

Atila Fassina
Atila Fassina

Posted on • Originally published at atila.fassina.eu on

4 1

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! 💥

References

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay