NaN's Unique Inequality
What you'll learn: Why NaN is the only value in JavaScript that doesn't equal itself, and how to properly test for it.
In the previous lesson, you saw that NaN behaves oddly in comparisons. Now we tackle its strangest quirk: NaN is the only value in JavaScript that is not equal to itself.
Why NaN == NaN Is False
When you compare NaN to anything—including another NaN—the result is always false:
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
This isn't a JavaScript bug—it follows the IEEE 754 floating-point standard. The reasoning: NaN represents "Not-a-Number," often the result of an undefined or invalid operation. Since two undefined operations could have different causes, they shouldn't be considered equal.
Think of it like two people saying "I don't know." Just because both answered "I don't know" doesn't mean they don't know the same thing.
How to Test for NaN
Because NaN isn't equal to itself, you cannot use === to detect it:
let result = 0 / 0; // NaN
if (result === NaN) {
// This will NEVER run!
}
Instead, use the global isNaN() function or the more reliable Number.isNaN() (though Number methods aren't covered yet, isNaN is available):
let result = 0 / 0;
console.log(isNaN(result)); // true
Key Takeaway: NaN is the only JavaScript value that fails equality checks against itself (NaN !== NaN). Always use isNaN() to test if a value is NaN, never ===.