Home « Previous Next »

Problems with isNaN()

typeof(NaN) // "number"

isNaN() and its gotchas

Lets see what are the gotchas with isNaN()

isNaN(NaN); // true
isNaN(10); // false
isNaN("10") // false

// Now carefully inspect the output of below line
isNaN("10B") // true

So what are the problems?

As you can see, what happened in the last line provided in the above snippet is that, JavaScript tried to do a type coercion.

It simply tried to convert β€œ10B” into a number. isNaN(Number(β€œ10B”))

And Number(β€œ10B”) returns NaN. Hence we get output as true. This is a problem. So how do we properly check for NaN?

So what is the fool proof way to check for NaN?

** NaN is the only JavaScript value which is unequal to itself (NaN === NaN)**

So we can test if a value is NaN by comparing with itself using !== operator. In the below example, if you assign any other value to foo apart from NaN, it will return false.

var foo = NaN;

foo !== foo  // This will return true and this is the way to check.