NaN
What is NaN
NaN is a special numeric value in JavaScript meaning:
"Not a Number" - meaning exactly that: not a number.
But NaN itself has the type "number".
typeof NaN; // "number"In other words,
NaNis simply an invalid numeric value. It appears when the result of a mathematical operation cannot be expressed as a number.
When NaN appears
Some typical cases:
Number('hello'); // NaN - could not convert the string to a number
parseInt('abc'); // NaN
0 / 0; // NaN - mathematically undefined
Math.sqrt(-1); // NaN - cannot take the square root of a negative number
'abc' * 3; // NaN - a string cannot be multiplied
undefined + 5; // NaNHow to check a value for NaN
isNaN(value) - the old function
isNaN(NaN); // true
isNaN('hello'); // true (!)
isNaN('123'); // falseThe problem: isNaN first converts the value to a number,
and then checks whether it is NaN.
So the string 'hello' → NaN, and the result is true.
Number.isNaN(value) - the modern and correct way
Number.isNaN(NaN); // true
Number.isNaN('hello'); // false
Number.isNaN(undefined); // false
Number.isNaN(5); // false
Number.isNaN(0 / 0); // true
Number.isNaN()does not convert the argument to a number, and works only if the value is actually equal to NaN.
Why NaN === NaN returns false
This may seem strange, but it's a quirk of IEEE 754 - the standard JavaScript uses to implement floating-point numbers.
Under the IEEE-754 standard, NaN is not equal even to itself.
Because NaN is not a specific value but a marker of a computation error,
and there can be many such "error" states (different bit combinations → different kinds of NaN).
So:
NaN === NaN; // false
NaN == NaN; // falseHow to correctly check whether a value is NaN
The correct way:
Number.isNaN(value);or if you want it short:
const isReallyNaN = x => x !== x;
isReallyNaN(NaN); // true, because only NaN !== NaNThe trick:
NaNis the only value in JS that is not equal to itself.
Summary
| Check | Result | Comment |
|---|---|---|
typeof NaN | "number" | Type is number, even though it means "not a number" |
NaN === NaN | false | Per IEEE-754 |
isNaN('text') | true | Converts to a number first (a poor choice) |
Number.isNaN('text') | false | The modern, correct choice |
Number.isNaN(NaN) | true | Checks without type conversion |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.