Glossary / NaN

NaN

NaN (“Not-a-Number”) is a special value in JavaScript’s Number type that represents an invalid or unrepresentable numeric result. It is produced by operations such as 0 / 0 or Number("not a number"). NaN propagates through most arithmetic, so once it enters a calculation it can contaminate downstream results unless checked at the boundary.

Important semantics

const result = Number("abc");
Number.isNaN(result); // true
result === NaN;       // false
Object.is(result, NaN); // true

NaN is the only value that is not equal to itself under ===. Use Number.isNaN(value), which does not coerce; global isNaN(value) first converts its argument, so isNaN("hello") is true while Number.isNaN("hello") is false. SameValueZero comparisons used by Map and Set treat NaN as equal to itself.

NaN is falsy, but that does not make a truthiness test a good validation strategy. if (!n) also rejects zero, and positive/negative infinity are truthy despite often being invalid domain values. Use Number.isFinite or explicit domain ranges when validating numeric input. Parsing behavior matters: parseFloat("12px") returns 12, while Number("12px") returns NaN.

Debugging numeric NaN

Trace the first operation that introduced it rather than patching the final output. Check input conversion, division by zero, invalid square roots, overflow, and values returned by third-party APIs. In tests, assert finite/range constraints close to the boundary where data enters the domain.

Interview questions

  1. What is the type of NaN? Number.
  2. Why does NaN === NaN return false? The language follows IEEE-style NaN comparison behavior; use Number.isNaN or Object.is.
  3. Why prefer Number.isNaN over global isNaN? It checks the value without coercing unrelated inputs.
  4. Does if (!value) validate a number? No; it conflates NaN with zero and other falsy values.

References