NaN means ‘not a number‘ in javascript. It is a special value of type number.
typeof(NaN); // number
You might wonder if NaN is “not a number” then why is it type number?
Because NaN is an error value (invalid number) that we get from numeric operation. And what type of value will you get from numeric operation? Definitely, number type.
Hence, NaN is a numeric value which is used for indicating absence of a valid number.
let age = 15; if(age < 18){ age = Number.NaN; console.log("Not eligible to vote"); }
For example,let’s say we have program where users input their age. If the age is less than 18, program assigns it a invalid number (NaN) because you must be older than 18 to vote and console log ‘Not eligible to vote’.
Here, NaN is a numeric value that tells 16 is a number but not a valid number.
When do we get NaN?
1. When converting value to number does not result in number.
Number(‘one’); // NaN Number(undefined); //NaN
2. When mathematical operation does not result in real number.
Math.sqrt(-1); //NaN
3. Any calculation involving NaN value.
NaN++; // NaN 3 * NaN; //NaN 3/NaN; //NaN NaN – 3; //NaN
4. Other than addition operator, any arithmetic operator with string value will result in NaN.
"three " + 3; //three 3 "abc " – 3; //NaN "abc " – "3" //NaN "abc " * 3 //NaN "abc" / 3 //NaN "three " + 3; //three 3 "abc " – 3; //NaN "abc " – "3" //NaN "abc " * 3 //NaN "abc" / 3 //NaN
How do we check for NaN value?
var x = Number('one'); // NaN; var y = Number('two'); //NaN x === y //false
In the code example, even though that both variables x and y are NaN value, when we compare them with strict equality operator we get false. This is because NaN is the only value in javascript that is not strictly equal to itself.
It does not equal to any value as well.
So, how do we determine if the value is NaN in javascript?
Javascript has built-in utility functions Number.isNaN() and isNaN() for determining NaN value but there is a difference between these two functions.
var x = Number('one'); // NaN; var y = 1; isNaN(x); // true isNaN(y); // false Number.isNaN(x); // true Number.isNaN(y); // false
Now, let’s examine the difference between Number.isNaN() and isNaN() function.
Example 1
isNaN(‘one’);
// true
Example 2
Number.isNaN(‘one’);
// false
In Example 1,we passed “one” to isNaN function. It is not a number but it is not a NaN value either. It is a string value but we still get true. This is because isNaN first coerces value to a number and checks for NaN. If the outcome is NaN then it will return true.
So in our Example 1, when isNaN coerces string “one” to number, it gives NaN value so true is returned.
Number.isNaN does not do any coercion. It only checks if the passed value is NaN value or not .
In our Example 2, passed value to Number.isNaN() is string “one” so we get false returned.