JavaScript Number NaN Property
The JavaScript Number NaN is a static property that represents a value that is Not-A-Number. Because it is a static property of the Number object, you can access it directly by using Number.NaN, instead of as a property of a variable.
If you try to access this property using a variable as x.NaN, where 'x' is a variable, you will get 'undefined' as the result. This is because NaN is a static property of the Number object, not a property of individual variables.
Syntax
Following is the syntax of JavaScript Number NaN property −
Number.NaN
Parameters
- It does not accept any parameter.
Return value
This property does not have any return value.
Example 1
The following program demonstrates the use of the Number.NaN property.
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
document.write("Result = ", Number.NaN);
</script>
</body>
</html>
Output
The above program returns 'NaN' in the output.
Result = NaN
Example 2
If you try to access this property using a variable rather than the Number object, you will get 'undefined' as the result.
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
let x = 10;
document.write("x = ", x);
document.write("<br>x.NaN is = ", x.NaN);
</script>
</body>
</html>
Output
The above program displays 'undefined' because the variable cannot access the 'NaN' property.
x = 10 x.NaN is = undefined
Example 3
The following program checks a number and returns Number.NaN if it is not a valid number; otherwise, it displays "passed".
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
function check(x){
if(isNaN(x)){
return Number.NaN;
}
else{
return x + " is a number...!";
}
}
let x = 10;
document.write("x = ", x);
document.write("<br>Result1 = ", check(x));
let y = NaN;
document.write("<br>y = ", y);
document.write("<br>Result2 = ", check(y));
</script>
</body>
</html>
Output
The above program displays the output based on conditions (for true, Number.NaN; and for false, a statement will be returned).
x = 10 Result1 = 10 is a number...! y = NaN Result2 = NaN