Number.isNaN() is a method used to determine whether a value is NaN (Not-a-Number) and is of type number.
It is different from the global isNaN() function in that it does not coerce the value to a number before testing it.
This means that Number.isNaN() is a more reliable way to test specifically for NaN values.
Syntax
Number.isNaN(value)
value: The value to test.
Returns
trueif the value is NaN and is of typenumber.falseotherwise.
Differences from isNaN()
Number.isNaN()checks if a value is exactlyNaN.isNaN()coerces the value to a number before checking, which can lead to unexpected results.
Examples
Here are 10 examples demonstrating how Number.isNaN() works:
Basic NaN Check
console.log(Number.isNaN(NaN)); // trueNumber that is not NaN
console.log(Number.isNaN(123)); // falseString that is not NaN
console.log(Number.isNaN('hello')); // falseNumber object with NaN value
let numObj = new Number(NaN); console.log(Number.isNaN(numObj)); // falseInfinity (Positive)
console.log(Number.isNaN(Infinity)); // falseInfinity (Negative)
console.log(Number.isNaN(-Infinity)); // falseNaN from arithmetic operation
let result = 0 / 0; console.log(Number.isNaN(result)); // trueBoolean value
console.log(Number.isNaN(true)); // false console.log(Number.isNaN(false)); // falseNull value
console.log(Number.isNaN(null)); // falseArray containing NaN
let array = [NaN]; console.log(Number.isNaN(array[0])); // true
Key Points
- NaN is a special value in JavaScript that stands for "Not-a-Number" and is a member of the
numbertype. Number.isNaN()is more precise for checking NaN values compared to the globalisNaN(), which can produce unexpected results due to type coercion.