In JavaScript, NaN stands for “Not a Number”. It usually appears when a math operation fails:
const result = 0 / 0;
console.log(result); // NaN
What’s Weird About NaN?
The tricky part: NaN is not equal to itself.
console.log(NaN === NaN); // false 😮
This is different from most other values in JavaScript, where x === x is always true.
Why is NaN Not Equal to Itself?
This behavior comes from the IEEE 754 standard (used for floating-point math). According to it, NaN is considered unequal to any value—including itself—because it’s the result of an undefined or unrepresentable number.
So How Do You Check for NaN?
Use the built-in Number.isNaN() method:
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN('hello')); // false
console.log(Number.isNaN(undefined)); // false
console.log(Number.isNaN(123)); // false
Don’t Use isNaN()
There’s another function, isNaN(), but it’s less reliable because it tries to coerce values first:
console.log(isNaN('hello')); // true (yikes!)
console.log(Number.isNaN('hello')); // false (correct)
Safe Comparison Trick
If you’re ever stuck without Number.isNaN(), you can still test using this quirk:
function isReallyNaN(value) {
return value !== value;
}
console.log(isReallyNaN(NaN)); // true
Conclusion
NaN is one of JavaScript’s quirkiest values. Because it doesn’t equal itself, normal comparisons don’t work. Use Number.isNaN() to test for it reliably. Avoid the older isNaN() function unless you know what you’re doing. And if you’re ever unsure, remember: if x !== x, it’s definitely NaN.
Post a Comment