CKTIS / JavaScript
NaN: the special Number value and how to detect it
`NaN` is a special `Number` value. Use `Number.isNaN()` to detect it without converting the argument, unlike the global `isNaN()` function.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
NaN
Number.NaN
Number.isNaN(value)
isNaN(value)NaN (short for “Not-a-Number”) is a special primitive value of the Number type. For example, 0 / 0 and Number("oops") produce it rather than throwing an exception. typeof NaN returns "number". The global property NaN and the static property Number.NaN expose the same value, which is distinct from the string "NaN".
Use Number.isNaN(value) to test a value. It returns true only for NaN and does not convert its argument. Neither == nor === considers NaN equal even to itself: NaN === NaN is false. By contrast, Object.is(NaN, Number.NaN) returns true because it uses a different comparison rule.
The global function isNaN(value) first tries to convert its argument to a Number. That is why isNaN("oops") returns true, while isNaN("") returns false because the empty string converts to 0. For BigInt or Symbol values, this conversion throws a TypeError; Number.isNaN() returns false for those values.
If you need a finite Number, use Number.isFinite(value). Checking only !Number.isNaN(value) is not enough: it also accepts infinities and values that are not of type Number.
Examples
{
const input = "oops";
const value = Number(input);
console.log(value);
console.log(Number.isNaN(input));
console.log(isNaN(input));
console.log(Number.isNaN(value));
console.log(value === NaN);
console.log(Object.is(value, Number.NaN));
}Result
NaN false true true false true
`input` remains a string; `Number(input)` is what produces `NaN`. The last two output lines show the difference between `===` and `Object.is()`.
Related lessons
- JavaScript · Lesson 12 · Intermediate · Version: 3
Sources
- ECMAScript 2024 — NaN
- ECMAScript 2024 — The Number Type
- ECMAScript 2024 — Number.NaN
- ECMAScript 2024 — Number.isNaN ( number )
- ECMAScript 2024 — isNaN ( number )
- ECMAScript 2024 — ToNumber ( argument )
- ECMAScript 2024 — Object.is ( value1, value2 )
- ECMAScript 2024 — Number.isFinite ( number )
- NaN - JavaScript | MDN