Understanding NaN in JavaScript: Common Pitfalls and How to Compare It Properly
Learn what NaN means in JavaScript, why it can be tricky, common mistakes when comparing it, and how to check for NaN correctly.
In JavaScript, NaN stands for "Not-a-Number." It represents a value that is not a legal number. This can happen, for example, when you try to perform a math operation on something that isn’t a valid number. NaN is part of JavaScript’s way of handling errors silently without crashing your code.
A common pitfall with NaN is that it is the only value in JavaScript that is not equal to itself. This means using the usual comparison operators (== or ===) to check if a value is NaN will not work as expected.
console.log(NaN === NaN); // false
console.log(NaN == NaN); // falseBecause of this unusual behavior, if you want to check whether a value is NaN, you should use the built-in function isNaN() or the more reliable Number.isNaN() introduced in ES6.
Here's how you use both:
console.log(isNaN("hello")); // true, "hello" cannot be converted to a number
console.log(isNaN(123)); // false, 123 is a number
console.log(Number.isNaN("hello")); // false, "hello" is not NaN, just not a number
console.log(Number.isNaN(NaN)); // trueNotice that isNaN converts the input to a number first, which can sometimes lead to confusing results. Number.isNaN() is more strict and only returns true if the value is actually NaN.
To summarize, avoid using === or == to check for NaN. Instead, use Number.isNaN() when you want to make sure the value is exactly NaN.
// Correct way to check for NaN
function checkIfNaN(value) {
if (Number.isNaN(value)) {
console.log("Value is NaN!");
} else {
console.log("Value is NOT NaN.");
}
}
checkIfNaN(NaN); // Value is NaN!
checkIfNaN(5); // Value is NOT NaN.
checkIfNaN("test"); // Value is NOT NaN.