Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a value is NaN

Short answer

NaN means not a number, the result of a failed calculation. Check it with Number.isNaN():

const value = Number('abc');
 
console.log(Number.isNaN(value));

Output:

true

Any real number

Number.isFinite() returns true only for ordinary numbers: not NaN and not Infinity:

console.log(Number.isFinite(42));
console.log(Number.isFinite(1 / 0));
console.log(Number.isFinite(NaN));

Output:

true
false
false

Common mistake

NaN is the only value that is not equal to itself, so comparing with === never works:

const value = Number('abc');
 
console.log(value === NaN);
console.log(isNaN('hello'), Number.isNaN('hello'));

Output:

false
true false

The old global isNaN() converts its argument to a number first, so for the string hello it returns true. Number.isNaN() does not convert anything.

Functions used in this recipe

  • Number.isNaN — Checks that a value is NaN, without type conversion.
  • Number.isFinite — Checks that a value is a finite number (not NaN and not Infinity).

Thanks for reading!

Donate to the site — we work hard for you.