In JavaScript, NaN is short for Not a Number.
NaN is a JavaScript number that is not a legal number.
Invalid Number Operations
You get NaN when JavaScript cannot calculate a number.
Example
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = x;
NaN is a Number
The type of NaN is number.
This may look strange, but NaN belongs to the JavaScript number type.
Example
let x = NaN;
document.getElementById("demo").innerHTML = typeof x;
Numeric Strings
JavaScript tries to convert numeric strings to numbers in arithmetic operations.
Example
let x = 100 / "10";
document.getElementById("demo").innerHTML = x;
Note: The result is
10, because"10"is converted to the number10.
Non-Numeric Strings
A non-numeric string cannot be converted to a number.
Example
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = x;
Note: The result is
NaN, because"Apple"cannot be converted to a number.
Using isNaN()
You can use the JavaScript function isNaN() to find out if a value is not a number.
Example
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
NaN is Not Equal to Itself
NaN is the only JavaScript value that is not equal to itself.
Example
let x = NaN;
document.getElementById("demo").innerHTML = x == x;
To test for NaN, use isNaN().
NaN in Math
If you use NaN in a mathematical operation, the result will also be NaN.
Example
let x = NaN;
let y = 5;
document.getElementById("demo").innerHTML = x + y;
Note:
NaNmeans Not a Number. But the type ofNaNisnumber. UseisNaN()to check if a value isNaN.