Check if a Number is NaN in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if a Number is NaN in JavaScript #

Use the Number.isNaN() method to check if a number is NaN, e.g. if (Number.isNaN(num)) {}. The Number.isNaN() method will return true if the provided value is NaN and has a type of number.

index.js
const num = 0 / 'test'; console.log(num); // 👉️ NaN if (Number.isNaN(num)) { // 👉️ this runs only if NaN and type of number console.log('Number is NaN'); }

We used the Number.isNaN method to check if a value has a type of number and is NaN.

You shouldn't use the equality operators when checking for NaN, because NaN is not equal to NaN in Javascript.

index.js
// ❌ don't do this console.log(Number.NaN === Number.NaN); // 👉️ false
NaN is the only value in JavaScript that is not equal to itself.

The Number.isNaN() method only returns true if the following conditions are met:

  • the value is of type number
  • the value is NaN

All the following examples return false.

index.js
console.log(Number.isNaN('string')); // 👉️ false console.log(Number.isNaN(undefined)); // 👉️ false console.log(Number.isNaN(null)); // 👉️ false console.log(Number.isNaN([])); // 👉️ false console.log(Number.isNaN({})); // 👉️ false

Here is a polyfill that demonstrates how the Number.isNaN method is implemented.

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

We first check if the Number.isNaN method is supported by the browser.

If it isn't supported, we implement it by attaching a function to the isNaN property of the Number object.

The function checks if the type of the provided value is of type number and is not equal to itself.

NaN is the only value in JavaScript that is not equal to itself, so this is sufficient to determine if the value is NaN.

An alternative approach is to use the older isNaN method.

If the argument provided to the isNaN method is not of type number, the method coerces the value to a number before checking if it is NaN.

This is different from the Number.isNaN method, which doesn't coerce the passed in value.

Here are some examples of using the isNaN method:

index.js
console.log(isNaN(0 / 0)); // 👉️ true console.log(isNaN('string')); // 👉️ true console.log(isNaN(undefined)); // 👉️ true console.log(isNaN({})); // 👉️ true console.log(isNaN(null)); // 👉️ false console.log(isNaN([])); // 👉️ false

The Number.isNaN method would only return true for Number.isNaN(0 / 0). All other examples would return false.

The older isNaN method is a bit more unintuitive than Number.isNaN because it tries to coerce non-numbers to a number before checking if the value is NaN.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.