JavaScript Reference ยท Global Functions and Values
The NaN value
Reference for JavaScript NaN: how it arises, why NaN !== NaN, reliable ways to test for it, how it spreads through calculations, and sorting caveats.
NaN ("not a number") is a special value of the Number type that signals a failed numeric operation, such as 0 / 0, Math.sqrt(-1) or Number("abc"). Despite its name, typeof NaN is "number".
NaN is the only value in JavaScript that is not equal to itself, which is why you test for it with Number.isNaN() rather than with ===.
Number("abc"); // NaN
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
NaN Number.NaN
Value: the Number value that represents an undefined or unrepresentable result.
Property attributes: NaN on the global object is not writable, not enumerable and not configurable.
Usage notes
- Never compare with
===or==. Both are alwaysfalseforNaN, evenNaN === NaN. - Reliable tests:
Number.isNaN(x)(no conversion),Object.is(x, NaN), orx !== x. The globalisNaN()converts first and reportstruefor text like"abc". - It spreads. Any arithmetic with
NaNgivesNaN, so one bad value can silently ruin a total. Validate inputs early. - Collections:
includes()andSetuse SameValueZero and treatNaNas equal to itself;indexOf()and===-based lookups do not find it. - Sorting: a comparator that returns
NaNis treated as0, which makes ordering inconsistent. Fix the data or handleNaNexplicitly. - JSON turns it into
null:JSON.stringify(NaN)is"null". - Not an error. JavaScript does not throw for invalid arithmetic; it returns
NaN. Dates use it too: an invalidDatehas a time value ofNaN. - Boolean context:
NaNis falsy, as are0,"",nullandundefined. - BigInt has no NaN;
0n / 0nthrows aRangeError.
Browser support
NaN works in every browser and runtime.
Related
isNaN(),Number.isNaN(),Infinity,Object.is()- Lessons: Numbers, Type conversion