How to detect NaN in Javascript?
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”.
As an example, zero divided by zero results in NaN. The example code here …
will output “NaN detected. Bad math operation.”
You can not do …
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.
Conversely, NaN is “not equal” to everything …
NaN is not even equal to itself!
But it is not equivalent to false …
While 0/0 results in NaN, comparing 0/0 with NaN will return false…
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.