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
true
if the value is NaN and is of typenumber
.false
otherwise.
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)); // true
Number that is not NaN
console.log(Number.isNaN(123)); // false
String that is not NaN
console.log(Number.isNaN('hello')); // false
Number object with NaN value
let numObj = new Number(NaN); console.log(Number.isNaN(numObj)); // false
Infinity (Positive)
console.log(Number.isNaN(Infinity)); // false
Infinity (Negative)
console.log(Number.isNaN(-Infinity)); // false
NaN from arithmetic operation
let result = 0 / 0; console.log(Number.isNaN(result)); // true
Boolean value
console.log(Number.isNaN(true)); // false console.log(Number.isNaN(false)); // false
Null value
console.log(Number.isNaN(null)); // false
Array 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
number
type. Number.isNaN()
is more precise for checking NaN values compared to the globalisNaN()
, which can produce unexpected results due to type coercion.
Tags:
JavaScript