JavaScript NaN Property
NaN, which stands for "Not a Number," is a special value in JavaScript that shows up when a mathematical operation can't return a valid number. This can happen if you try something like dividing zero by zero or converting a string that doesn't contain numbers.
NaN helps you spot when something went wrong with your calculations or data.
Syntax
You can assign NaN in two ways:
let a = NaN
// OR
let a = Number.NaN
Examples of JavaScript NaN Property
Here are some examples of Javascript NaN Property :
Example 1: In this example, we are checking if the monthNumber is within the valid range (1 to 12). If it's outside this range, we assign NaN and display an appropriate message.
let monthNumber = 14;
if (monthNumber < 1 || monthNumber > 12) {
// Assigning monthNumber NaN as
// month number is not valid
monthNumber = Number.NaN;
console.log("Month number should be"
+ " between 1 and 12");
}
else {
console.log(monthNumber);
}
Output:
Month number should be between 1 and 12
Example 2: In this example, we are trying to find the square root of a negative number using Math.sqrt(). Since the square root of -1 is not a real number, it returns NaN.
console.log(Math.sqrt(-1));
Output:
NaN
Example 3: In this example, when we add NaN to a number (5 + NaN), the result is NaN, as any operation involving NaN results in NaN.
console.log(5 + NaN);
Output:
NaN
Example 4: In this example, multiplying 0 by Infinity results in NaN, as this is an indeterminate form in JavaScript.
console.log(0 * Infinity)
Output
NaN
Supported Browser
We have a Cheat Sheet on Javascript Numbers where we covered all the important topics of Javascript to check those please go through JavaScript Number Complete Reference.