Masterbook/Chapter 11• 2 min read
View Raw Code on GitHub

What is NaN and how do you check for it

What is NaN and how do you check for it

NaN stands for Not-a-Number. It is a special numeric value that represents the result of an invalid or undefined numeric operation. NaN has typeof "number" because it lives in the number type domain, but it signals that a meaningful numeric value could not be produced.

You get NaN from operations like 0 / 0, parsing non-numeric strings as numbers, square roots of negative numbers (in real arithmetic), or any arithmetic expression that already contains NaN. Once NaN is produced, it contaminates further arithmetic: any operation involving NaN typically yields NaN again.

Examples

console.log(typeof NaN); // "number"
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(parseInt("abc")); // NaN
console.log(Number("12x")); // NaN

A unique property of NaN is that it is not equal to anything, including itself. Therefore NaN === NaN is false. This design preserves the idea that different invalid results should not compare equal.

To check for NaN, prefer Number.isNaN(value). It returns true only when the value is actually the special NaN value. The older global isNaN(value) first coerces the argument to a number, so it can report true for non-numeric strings, which is often not what you want.

console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false
console.log(isNaN("hello")); // true (coerces to number → NaN)

Common misconceptions

  1. NaN means "not a numeric type". It is a number type value meaning "invalid numeric result".
  2. isNaN and Number.isNaN are interchangeable. isNaN coerces; Number.isNaN is strict and safer.
  3. You can detect NaN using equality or inequality operators. NaN never equals anything, not even itself.

Practice questions

  1. Name three operations that can produce NaN and explain why.
  2. Why does NaN !== NaN evaluate to true, and how do you correctly test for NaN?
  3. Write a function isNumeric(val) that returns true only for finite numbers (hint: use typeof, Number.isFinite).