Friday, 30 May 2014

Understanding JavaScript:NaN



NaN,not a number, is a special value used to denote an unrepresentable value. With JavaScript, NaN can cause some confusion, starting from its typeof and all to the way the comparison is handled.

Several operations can lead to NaN as the result. Here are some examples:

Math.sqrt(-2)          //NaN

Math.log(-1)           //NaN

parseFloat('foo')    //NaN

0/0                          //NaN


The first trap is usually the unexpected result of calling typeof:

console.log(typeof NaN); // 'number'

In a way, while NaN isn’t supposed to be a number, its type is number. Got it?
Let’s compare two NaNs:

var x = Math.sqrt(-2);

var y = Math.log(-1);

console.log(x == y);         // false

Maybe that’s because we’re supposed to use strict equal (===) operator instead? Apparently not. 

var x = Math.sqrt(-2);

var y = Math.log(-1);

console.log(x === y); // false

even if we test like this:

console.log(x == x);       // false 

if we compare real NaNs then:

console.log(NaN === NaN); // false

Because there are many ways to represent a NaN, it makes sense that one NaN will not be equal to another NaN.


No comments:

Post a Comment