What is NaN in JavaScript?
NaN stands for Not-a-Number.
It's a special value in JavaScript that means the operation result is not a valid number.
NaNhas numeric type (typeof NaN === "number"), but isn't a number in the classic sense.
When NaN Occurs
NaN appears in the following situations:
const result1 = 0 / 0; // NaN
const result2 = Math.sqrt(-1); // NaN
const result3 = parseInt("abc"); // NaN
const result4 = "hello" - 5; // NaN
NaN Peculiarities
NaN !== NaN→trueThis is one of JavaScript's strangest features:NaNnever equals even itself.
console.log(NaN === NaN); // false
- To check if a value is
NaN, you need to use special methods.
How to Properly Check for NaN
| Method | Features |
|---|---|
isNaN(value) | Converts value to number, then checks |
Number.isNaN(value) | Strict check without conversion — preferable |
Example:
isNaN("hello"); // true — because "hello" → NaN
Number.isNaN("hello"); // false — string is not NaN
Number.isNaN(NaN); // true
Important:
Never compare NaN using ===. Use Number.isNaN() for accurate checking.
Conclusion
NaNis a number type value meaning invalid numeric expression.- It doesn't equal itself, which makes it special.
- Use
Number.isNaN()for reliable checking.