Numbers in Java are actually 64-bit floating point numbers, better known as the “double” datatype in C#, Java and probably C++ and C (I’m not sure it’s standardized in those languages though). They are based upon the IEEE 754 floating point standard.

One curious fact about JavaScript numbers is that due to the technical implementation every representable number can be both positive and negative. This is not so strange for numbers like 1 or -2.5, but it is a bit odd that you can have both positive zero +0 and negative zero -0, which of course is meaningless. But possible in Javascript.

Of course this post is specifically about NaN, the  “not a number” symbol.

NaN can appear in several ways, for example:

0/0
>>> NaN

parseFloat("bread")
>>> NaN     // oh right

NaN - 1
>>> NaN

Technical aside: In the IEEE 754 standard 64-bit NaN is represented by the number 2^53 – 2. But this is actually not the case in JavaScript, where NaN is a symbol separate from the range of numbers:

Math.pow(2,53) -2
>>> 9007199254740990     // ~9007 trillion or billion depending on your country

Ok, so how do you manage NaNs in a good way? One tricky aspect of NaN is that NaN is never equal to itself, so at first glance using comparison operators is pointless:

NaN === NaN
>>> false       // ?

NaN !== NaN
>>> true        // strange, but more on this later

A built in way of detecting NaN is by using the isNaN function. However, you have to know exactly what you are doing. There are pitfalls:

isNaN(NaN)
>>> true

isNaN(undefined)
>>> true       // seems like a bad idea

isNaN('a')
>>> true       // seriously?

isNaN('10')
>>> false      // ?

A neat trick in JavaScript is to exploit the property shown earlier that NaN !== NaN evaluates to false. In other words, we are exploting the fact that NaN is the only built in value which is always “not equal” to itself.

So comparing a variable to itself using the “not equals” operator is good way of determining if that variable is NaN or not. However, it could be infinity as well!

var a = 1.4,
    b = 1/0,  // infinity
    c = 0/0;  // NaN
a !== a
>>> false

b !== b
>>> false

c !== c
>>> true
Advertisements