Not a Number (NaN)
May 20, 2023
NaN
stands for “Not a Number,” and is a value used in JavaScript to indicate that a mathematical operation or function resulted in a value that is not a number. It is a global property of the Number
object, meaning it can be accessed directly without creating a new instance of the Number
object.
Purpose
The purpose of NaN
is to provide a standardized way of handling errors that occur during mathematical operations and functions. Rather than throwing an error or crashing the program, NaN
can be returned as a result, indicating that the operation or function did not result in a valid number.
Usage
NaN
can be returned as a result of any mathematical operation or function that does not result in a valid number. Some common examples include:
- Dividing a number by zero
- Taking the square root of a negative number
- Trying to convert a string that is not a valid number to a number
For example, if you try to divide a number by zero in JavaScript, the result will be NaN
:
let result = 5 / 0;
console.log(result); // NaN
Similarly, if you try to take the square root of a negative number, the result will also be NaN
:
let result = Math.sqrt(-1);
console.log(result); // NaN
NaN
can also be used to check if a value is not a valid number. This can be done using the isNaN()
function, which returns true
if the value passed to it is NaN
, and false
otherwise. It is important to note that isNaN()
is not a reliable way to check if a value is a number, as it will return true
for values that are not numbers, such as strings:
console.log(isNaN(7)); // false
console.log(isNaN("hello")); // true
console.log(isNaN(NaN)); // true
To check if a value is a valid number, you can use the Number.isNaN()
function, which returns true
only if the value passed to it is NaN
:
console.log(Number.isNaN(7)); // false
console.log(Number.isNaN("hello")); // false
console.log(Number.isNaN(NaN)); // true
Handling NaN
When NaN
is returned as a result of a mathematical operation or function, it is important to handle it properly to prevent errors or unexpected behavior. One approach is to check for NaN
using the isNaN()
function and handle it accordingly:
let result = someFunction();
if (isNaN(result)) {
// Handle NaN
} else {
// Use the result
}
Another approach is to use the nullish coalescing operator (??
) to provide a default value in case of NaN
:
let result = someFunction() ?? 0;
This will set result
to 0
if someFunction()
returns NaN
.