I had been programming in JavaScript for some time and I had never noticed that peculiarity that it has with the value NaN
.
I decided to investigate and the most I found was: NaN - JavaScript | MDN / [English] .
I understood that it NaN
is the reference of “Not a Number” (it is not a number) but I am not clear why a NaN is not equal to another NaN using the operator ==
, ===
.
parseFloat('NaN') == parseFloat('NaN'); // false
parseFloat('NaN') == NaN; // false
NaN == NaN; // false
What happens at the logical level that equality is not fulfilled? Why does it not also apply to the expression undefined == undefined
?
This is how it has been defined and it makes sense, for example imagine the following case:
As much
a
asb
they resultNaN
. Now, do you think it is correct that they are the same?This is why the function is used
isNaN()
to verify if we are dealing with oneNaN
or not instead of trying to compare it against anotherNaN
.This does not apply to
undefined
because this has a precise meaning: An undefined identifier. InsteadNaN
it is a kind of invalid value for what in other languages would be a run-time error or exception.In simple words
NaN Not a Number
(NaN is not a number) and since it is not a number, it is anything. It is not possible to compare anything on one side with anything on the other side, so there is no guarantee that the two are the same. For example, it is not possible to make this comparison:This comparison is the same as:
In JavaScript
undefined
it is a data type , just like theNumber
,String
,Boolean
,Object
or theArray
. In JavaScript, unlike other strongly typed programming languages, we can have variables of typeundefined
.In summary, in JavaScript, all those variables that have not been defined (therefore do not exist) or that have been defined without assigning them a value, are always of type
undefined
.So logically when comparing two things that have the same data type , in this case
undefined
, it returnsVerdadero
.Reference: Java Language Specification (JLS)
Reviewing the NaN documentation
You will see what he comments
In other words, you must use the
isNaN()
to achieve what you propose.I want to think that this is so because it is an object, which is compared by reference when using the
==
so two references will not be equal.The same doesn't happen with undefined because this is a primitive value, it's not an object like NaN, so you can compare it to equal.