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.
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
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 // ?
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