Running Isnanundefined Come True In Javascript
In JavaScript, evaluating falsy values with if statements and the isNaN() function can produce some surprising results. Consider the following four statements—only one of them will actually print a value to the console:
function print(obj) {
console.log(obj);
}
if (undefined) {
print("undefined"); // ❌ Does NOT print — undefined is falsy
}
if (null) {
print('null'); // ❌ Does NOT print — null is falsy
}
if (isNaN(null)) {
print('isNaN(null)'); // ❌ Does NOT print — isNaN(null) is false, because null coerces to 0
}
if (isNaN(undefined)) {
print('isNaN(undefined)'); // ✅ PRINTS — isNaN(undefined) returns true
}
Why Does This Happen?
The key insight here is how JavaScript coerces values before passing them to isNaN():
nullis coerced to0byisNaN(), andisNaN(0)returnsfalse.undefinedcannot be coerced to a number, soisNaN(undefined)returnstrue.
This is one of JavaScript’s well-known quirks. In modern JavaScript, it is recommended to use Number.isNaN() instead, which does not perform type coercion and therefore behaves more predictably:
Number.isNaN(undefined); // false — because undefined is not the value NaN itself
Number.isNaN(NaN); // true