JS TutorialLesson #106
JavaScript NaN
In JavaScript, NaN is short for Not a Number.
In JavaScript, NaN is short for Not a Number.
NaN is a JavaScript number that is not a legal number.
Share
Invalid Number Operations
You get NaN when JavaScript cannot calculate a number.
Example
Example Code
javascriptlet 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
Example Code
javascriptlet x = NaN;
document.getElementById("demo").innerHTML = typeof x;Numeric Strings
JavaScript tries to convert numeric strings to numbers in arithmetic operations.
Example
Example Code
javascriptlet x = 100 / "10";
document.getElementById("demo").innerHTML = x;The result is 10, because "10" is converted to the number 10.
Non-Numeric Strings
A non-numeric string cannot be converted to a number.
Example
Example Code
javascriptlet x = 100 / "Apple";
document.getElementById("demo").innerHTML = x;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
Example Code
javascriptlet 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
Example Code
javascriptlet 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
Example Code
javascriptlet x = NaN;
let y = 5;
document.getElementById("demo").innerHTML = x + y;Note
> NaN means Not a Number.
> But the type of NaN is number.
> Use isNaN() to check if a value is NaN.
Interactive Code Examples
JS Example 1
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 2
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 3
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 4
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 5
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 6
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview: