Not a Number in JavaScript
What is a Not a Number
In my last post I was talking on how to use numbers in JavaScript. Now I want to talk about the notorious Not a Number invalid value. Also know as NaN.
A Not a Number indicates that the value of a variable or the result of an arithmetic expression is not a number.
Why I have a NaN?
You can get a NaN in two ways: by declaration or by an arithmetic expression:
var x = NaN; // use the keyword NaN for the declaration var y = 10 / "cars"; // returns NaN
Any operation between numbers and strings will result in a NaN. The only exception is when the string is made only of numbers.
var invalid = 5 * "cars"; // returns NaN var valid = 5 * "7"; // returns 35
Bare in mind, that any arithmetic operation involving a variable with a value of NaN will result also in NaN. This also includes when working with concatenation:
var n = NaN; var y = n * 10; // returns NaN var s = "MyString" + n; // returns NaN
How to test for NaN
There is a global function in JavaScript to test any value for possible NaN. The function isNaN() will return true if the value is Not a Number, or false, if not.
var x = 16; var n = NaN; var y = n * 10; // returns NaN var xIsNotValid = isNaN(x); // returns false var nIsNotValid = isValid(n); // returns true var yIsNotValid = isValid(y); // returns true
Comparing numbers and NaN
When comparing a number value with a NaN using the == or the === operators the result will always be false.
var n = NaN; var y = 7; var r = n == y; alert(r); // will display false var r2 = n === y; alert(r2); // will display false
If we want to be sure that the NaN and a number compare as true, we must rely on the typeof keyword. The typeof of any NaN, will always be number.
var n = NaN; var y = 7; var tOfn = typeof n; var tOfy = typeof y; var r = tOfn == tOfy; alert(r); // will display true var r2 = tOfn === tOfy; alert(r2); // will display true
Dealing with a lot of arithmetic expressions involving numbers and strings, could result in NaN values. Knowing about how they behave, can save us a lot of debugging time and a lot of headaches.