Detect failed numeric results
Validate parsed or calculated numeric input before using it in later arithmetic.
JS Puzzles · Const
NaN represents an invalid or undefined numerical result. It is unequal to every value, usually propagates through arithmetic, and should be tested with Number.isNaN() rather than equality.
NaN is JavaScript's numeric value for an invalid or undefined numerical result. It has unusual comparison semantics: it is unequal to itself and makes relational comparisons false, while usually propagating through arithmetic. Number.isNaN() is the precise predicate because it does not coerce its argument.
NaN; Number.isNaN(value)| Name | Type | Description |
|---|---|---|
value | any | The value to inspect for the NaN numeric value. |
A numeric value representing Not-A-Number; NaN-producing operations and comparison behavior are described on the page.
const values = [Number("oops"), 0 / 0, NaN];
for (const value of values) {
console.log(Number.isNaN(value), value !== value);
}
console.log(NaN === NaN); // false
console.log(NaN < 1, NaN > 1); // false false
console.log(NaN ** 0); // 1Use Number.isNaN() to identify the actual NaN value without coercing other types. NaN is unequal to every value, including itself, propagates through most mathematical operations, and relational comparisons with it are false; exponentiation by zero is the notable exception.
Validate parsed or calculated numeric input before using it in later arithmetic.
Perform a final validation after a calculation chain, because NaN usually propagates through arithmetic.
Avoid false positives from coercion when distinguishing actual NaN from non-number inputs.
NaN is a numeric value representing an invalid or undefined numerical result. It is returned by cases such as failed number conversion, non-real mathematical results, and indeterminate forms.
Follow-up: How can NaN arise from conversion? Number(undefined) and parseInt("blabla") both produce NaN when conversion fails.
NaN is not equal to any value, including itself, under ==, !=, ===, and !==. Use Number.isNaN(value), which tests for NaN without converting the argument.
Follow-up: Why is the global isNaN() less precise? It first converts non-number arguments, so values such as an empty string can produce misleading results.
NaN usually propagates through mathematical operations, so a final check can detect an earlier numerical failure. Relational comparisons involving NaN always return false.
Follow-up: What exception avoids propagation? Exponentiation with a zero exponent returns 1, including NaN ** 0.
Number.isNaN()isNaN()Number.NaNInfinityparseInt()Number()