How to detect NaN in Javascript?

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

The correct way to detect NaN in Javascript is to use the isNaN() function.  NaN is a “number” indicating a mathematical operation that results in “Not a Number”.

While the typeof NaN is a “number”, NaN stands for “Not a Number”.

typeof NaN

typeof NaN

As an example, zero divided by zero results in NaN.  The example code here …

detecting NaN

detecting NaN

will output “NaN detected. Bad math operation.”

You can not do …

wrong way to detect NaN

wrong way to detect NaN

This is the wrong way to detect NaN.

This is because NaN is not equal to anything — not even to itself.  All comparisons with NaN will result in false.

NaN is not equal to anything

NaN is not equal to anything

Conversely, NaN is “not equal” to everything …

NaN is not equal to everything

NaN is not equal to everything

NaN is not even equal to itself!

NaN if falsy

NaN is falsy

NaN is falsy

But it is not equivalent to false …

NaN is not equivalent to false

NaN is not equivalent to false

While 0/0 results in NaN, comparing 0/0 with NaN will return false…

zero divided by zero is NaN

zero divided by zero is NaN

So the ONLY way to detect an NaN is to use the isNaN function.

While in math, you have been told that you can not divide by zero, 4 / 0 will not result in NaN.  It results in Infinity which is another Javascript number type.