How to check if a number is NaN in JavaScript

How to check if a number is NaN in JavaScript:

JavaScript provides a method called Number.isNaN() that can be used to check if a number is NaN or not. In this post, I will show you how to use this method with examples.

Definition of Number.isNaN:

The Number.isNaN() method is defined as like below:

Number.isNaN(v)

It takes a parameter, v, which is the value to check.

Return value of Number.isNaN:

This method returns a boolean value. It returns true if the value v is NaN and its type is Number. Else, it returns false.

Example of Number.isNaN:

Let’s take a look at the below example:

console.log(Number.isNaN(12)); // false
console.log(Number.isNaN(12.4)); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(Number.NaN)); // true
console.log(Number.isNaN(100/0)); // false
console.log(Number.isNaN(0/0)); // true

As you can see here, it returns true if the parameter is NaN and it is a number.

If we don’t pass a number, it will return false.

console.log(Number.isNaN("12"));// false
console.log(Number.isNaN("NaN"));// false
console.log(Number.isNaN(undefined));// false
console.log(Number.isNaN("hello"));// false
console.log(Number.isNaN(null));// false
console.log(Number.isNaN(" "));// false
console.log(Number.isNaN("     "));// false

It returns false for all of these examples.

How to check if a value is NaN or not using if-else block:

We can use a if-else block to check if a value is NaN or not. But, don’t use === NaN as it will return false always.

For example:

v = NaN

if(Number.isNaN(v)){
  console.log('v is NaN');
}

It will work and print v is NaN.

But, if you use === to compare the result with NaN:

v = NaN

if(Number.isNaN(v) === NaN){
  console.log('v is NaN');
}

It will not work.

console.log(NaN === NaN);

It returns false in JavaScript.

JavaScript NaN compare check

Polyfill for Internet Explorer:

The Number.isNaN() method is not available in Internet Explorer. We can use the following polyfill instead:

Number.isNaN = Number.isNaN || function isNaN(input) {
    return typeof input === 'number' && input !== input;
}

It checks if the type of the input value is number or not and the value of input !== input. NaN !== NaN returns true.

Reference:

You might also like: