JavaScriptEasy
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 + 5isNaN, 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):trueonly ifxis actuallyNaN. Use this.- Global
isNaN(x): converts first, soisNaN("hello")istrueeven though "hello" is a string. Usually not what you want. Object.is(x, NaN): also works.Number.isFinite(x): rejectsNaNandInfinityin 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 NaN3console.log(NaN === NaN); // false45console.log(Number.isNaN(NaN)); // true6console.log(Number.isNaN("hello")); // false7console.log(isNaN("hello")); // true <- global isNaN converts first89console.log([NaN].indexOf(NaN)); // -110console.log([NaN].includes(NaN)); // true1112// NaN spreads through calculations13const total = [10, "x", 5].reduce((sum, v) => sum + Number(v), 0);14console.log(total); // NaN1516// Safe numeric parsing17function 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.