Hiprup

What is NaN and how do you check for it?

NaN ("Not a Number") is a special numeric value representing an invalid number result.

  • Source — invalid math like 0/0 or failed conversions like Number("x").

  • Self-inequality — NaN is the only value where NaN === NaN is false.

  • Check — Number.isNaN(value) is the safe, type-aware test.

Avoid the global isNaN() — it coerces first, so isNaN("hello") is true. Prefer Number.isNaN.

console.log(typeof NaN);             // 'number'
console.log(NaN === NaN);             // false (unique!)
console.log(NaN !== NaN);             // true

// What produces NaN
console.log(0 / 0);                   // NaN
console.log(Number('abc'));            // NaN
console.log(undefined + 1);           // NaN

// Correct check
console.log(Number.isNaN(NaN));        // true
console.log(Number.isNaN(42));         // false
console.log(Number.isNaN('hello'));     // false (string, not NaN)

// Wrong check (global isNaN coerces)
console.log(isNaN('hello'));            // true! (coerces to NaN first)
console.log(isNaN(undefined));          // true! (coerces to NaN)

// Self-inequality trick
const isNaNCheck = (v) => v !== v;     // Only true for NaN

typeof NaN = 'number' (counterintuitive). NaN !== NaN (only self-unequal value). Number.isNaN checks without coercion (correct).

Global isNaN coerces first — 'hello' becomes NaN, so it returns true (wrong for our intent). The self-inequality trick exploits NaN's unique behavior.

typeof NaN = 'number' and NaN !== NaN are the two gotchas. Always use Number.isNaN (not global isNaN).

Know what produces NaN: invalid math, failed conversion, undefined + number.

What is NaN and how do you check for it? | Hiprup