Why isNaN(null)
returns false
?
Because null
can be converted to a numerical representation in Javascript. In this case, null
is "equivalent" to the 0
after coercion.
The difference can be noticed from this example:
console.log(Number(null), isNaN(null)); // 0 false
console.log(Number(undefined), isNaN(undefined)); // NaN true
Javascript is a language that eventually makes automatic type coercion. The constructor Number
allows us to make this coercion to the type number
explicitly. Checking this behavior, it is noted that null
is convertible the numerical type (resulting in 0
), while undefined
no (resulting in NaN
).
The function (present in the global scope) isNaN
checks whether the argument can be correctly converted to a numerical representation. If conversion is possible, it is returned true
and otherwise not. That’s why isNaN(null)
returns false
and isNaN(undefined)
returns true
.
It is worth remembering that isNaN
(of the overall scope) is different of the static method Number.isNaN
. The nomenclature is confusing and, following the name, both had to do the same thing, but:
isNaN
checks whether the argument can be converted correctly to a numerical representation (without returning NaN
). Check the algorithm specified for the isNaN
.
Number.isNaN
checks (using a different but similar algorithm to ===
) whether the argument given is equal to NaN
. See the specification his as well.
The isNaN
works with a larger set of values. Antagonistically, the Number.isNaN
will return true
only when the past value is literally equal to NaN
. Otherwise, you will always return false
.
Some examples to verify the difference:
console.log(isNaN(5), Number.isNaN(5)); // false false
console.log(isNaN(NaN), Number.isNaN(NaN)); // true true
console.log(isNaN(null), Number.isNaN(null)); // false false
console.log(isNaN(undefined), Number.isNaN(undefined)); // true false
This is the expected behavior or may vary according to the environment (browser, Node.js, Deno etc.)?
The behavior of both functions is standardized by the specification. Therefore, it is expected to work in all browsers and runtimes.
The only caveat is that Number.isNaN
was introduced in Ecmascript 2015 (ES6).
Now it remains to be seen who decided
undefined
is Nan andnull
is zero...– hkotsubo
@hkotsubo I was putting a reference of the definitions of
undefined
andnull
in the answer, but none of them facilitated this interpretation that one isNaN
and the other is0
, so I decided to remove hahaha. But out of curiosity, you are here: Undefinedprimitive value used when a variable has not been assigned a value
and nullprimitive value that represents the intentional absence of any object value
– Rafael Tavares
Yeah, by the definition, maybe make sense. If it has no value, there is no way to convert to number. And if it is "absence of intentional value", the zero would be the value "similar", because it is the number that serves to indicate that it has nothing...
– hkotsubo