NaN: The Falsy Non-Number
What you'll learn: How NaN behaves as a falsy value and why it's unique in comparisons.
The Core Idea
You already know that NaN (Not a Number) represents an invalid numeric operation, and you've learned that it's one of JavaScript's falsy values. But NaN is peculiar — it's the only value in JavaScript that isn't equal to itself!
When used in conditional statements, NaN behaves like other falsy values:
if (NaN) {
console.log("This won't run"); // NaN is falsy
}
if (!NaN) {
console.log("This WILL run"); // !NaN is truthy
}
What Makes NaN Different
Unlike other falsy values, NaN has a bizarre property in comparisons:
console.log(NaN == NaN); // false (!)
console.log(NaN === NaN); // false (!)
Every other falsy value equals itself:
console.log(false == false); // true
console.log(0 == 0); // true
console.log("" == ""); // true
console.log(null == null); // true
console.log(undefined == undefined); // true
But not NaN. This is why you must use Number.isNaN() to detect it — direct comparison doesn't work.
Why This Matters
Think of NaN as "something went wrong with math, but we don't know what." Since different math errors produce NaN, JavaScript treats each NaN as potentially representing a different error, so they can't be equal to each other.
const result1 = 0 / 0; // NaN
const result2 = Math.sqrt(-1); // NaN
console.log(result1 === result2); // false, even though both are NaN
Key Takeaway: NaN is falsy like 0, false, and "", but unlike all other values in JavaScript, it never equals itself — always use Number.isNaN() to check for it.