a !== a
too good to be true?
The actual heading should be: A short story about the weird parts of
NaN
NaN
in JavaScript stands for “Not a Number”. The type of NaN
is surprisingly Number
. Which is weird because it is used to define something which isn’t a number.
typeOf(NaN); // "number"
It is used for instance for a result of a bad calculation.
var a = 3 * "jalal"; // NaN
The most confusing part aboutNaN
is that NaN
compared to anything else is always false!
NaN == false; // false
NaN == true; // false
An even compared to itself equals always false.
NaN == NaN; // false
NaN === NaN; // false
This raises one question:
How to check if a variable is NaN?
There is a function in JavaScript called isNaN(),
but it has, unfortunately, some issues on its own.
Let’s go through some examples:
isNaN(NaN); // true
That worked!
isNaN(1); // false because 1 is a number
This is also not surprising!
isNaN('1'); // false
This worked too because isNaN
coerces the passed in parameter and then checks if it is not a number.
isNaN('a'); // true because 'a' is not a number
Again, an implicit coercion is happening here. isNaN
tries to convert the parameter into a number. The result of this effort having ‘a’ as a parameter is NaN:
Number('a'); // NaN
parseInt('a'); // NaN
Number('1'); // 1
This is why isNaN('a')
returns true.
It’s similar to isNaN(Number('a'))
.
So basically the isNaN
function is useless unless you are 100% certain that the passed in parameter is supposed to be a number.
Again, how to check if a variable is NaN?
We mentioned before that NaN
is the only JavaScript variable that returns false
if it is compared to itself. We can make use of that!
var a = 3 * 'jalal'; // a = NaN
if (a !== a) console.log('A is NaN'); // a !== a equals to true
This is the only way (I am aware of) to certainly check if a variable is NaN.
You can imagine that those weird parts are important to know because they are fruitful soil for bugs of any kind.
Jalal Fathi is freelance software developer and startup founder. Passionate about web technologies and in love with JavaScript. Learn more.