1
In Javascript, when comparing two values NaN
(Not-A-Number), the result is false
. However this does not occur with values like null
and undefined
.
console.log(NaN === NaN, null === null, undefined === undefined)
MDN talks about the issue by explaining the need for the function isNaN()
to check whether a value is equivalent to NaN
:
Unlike all other possible values in Javascript, it is not possible to rely on the equality operators (== and ===) to determine whether the value is Nan or not, because both, Nan == Nan and Nan === Nan, will have the return value: false. Hence the need for isNAN function.
However this still does not answer why NaN === NaN
returns false
.
If so, what is the reason for this behaviour? As far as I know, this is related to the coercion of types in Javascript (correct me if I’m wrong), but I would like to understand what happens more accurately.
It has nothing to do with Javascript directly, this behavior comes from the technical standard of floating point numbers (IEEE 754)
– bfavaretto
Dude I don’t know if you’re interested in knowing about the math behind it, but in short the fact that Nan === Nan returns false is because the norm IEEE 754 (that javascript follows in its implementation) has this definition. In it you can find more about the motivation behind, the calculations, mathematical concepts and etc that explain why of this.
– João Paulo Nunes Soares
It’s weird, right?! That’s why
typeof NaN
is'number'
andnull === null
istrue
, despitetypeof null
was'object'
and{} === {}
wasfalse
.– Cmte Cardeal
@Cmtecardeal, all of it
null
is the "same" object, there givestrue
. The two literal objects there are different, so returnfalse
, but if you dolet a = {}; a === a;
, will havetrue
. What about theNaN
cannot be comparable, it is not really about the type, but about its very existence and the consequences of that. See more here.– Luiz Felipe