What is NaN?

NaN ("Not a Number") is a special numeric value that represents the result of an invalid or undefined math operation; its type is still "number".

Where it comes from

  • Converting non-numeric text: Number("abc"), parseInt("hello").
  • Invalid math: 0 / 0, Math.sqrt(-1), Infinity - Infinity.
  • Any arithmetic involving NaN: NaN + 5 is NaN, so it spreads through calculations.
  • Arithmetic with undefined: undefined + 1.

Its strangest property

NaN is the only value not equal to itself: NaN === NaN is false. That means you cannot check for it with ===.

How to check for it

  • Number.isNaN(x): true only if x is actually NaN. Use this.
  • Global isNaN(x): converts first, so isNaN("hello") is true even though "hello" is a string. Usually not what you want.
  • Object.is(x, NaN): also works.
  • Number.isFinite(x): rejects NaN and Infinity in one go; ideal for validating numeric input.

Array methods

[NaN].indexOf(NaN) is -1 (uses ===), but [NaN].includes(NaN) is true (uses SameValueZero).

In practice

Validate input with Number.isFinite(Number(value)) before using it, so a single NaN does not quietly poison a whole calculation.

Code example

js
1console.log(typeof NaN); // "number"
2console.log(Number("abc"), 0 / 0, Math.sqrt(-1)); // NaN NaN NaN
3console.log(NaN === NaN); // false
4
5console.log(Number.isNaN(NaN)); // true
6console.log(Number.isNaN("hello")); // false
7console.log(isNaN("hello")); // true <- global isNaN converts first
8
9console.log([NaN].indexOf(NaN)); // -1
10console.log([NaN].includes(NaN)); // true
11
12// NaN spreads through calculations
13const total = [10, "x", 5].reduce((sum, v) => sum + Number(v), 0);
14console.log(total); // NaN
15
16// Safe numeric parsing
17function toNumber(input, fallback = 0) {
18 const n = Number(input);
19 return Number.isFinite(n) ? n : fallback;
20}
21console.log(toNumber("42"), toNumber("4 2"), toNumber("abc"), toNumber("1e3")); // 42 0 0 1000

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app