javascript – Why NaN! = NaN?


I had been programming in JavaScript for a long time and I had never realized that peculiarity that it has with the NaN value.

I decided to investigate and the most I found was: NaN – JavaScript | MDN / [English] .

I understood that NaN is the reference of "Not a Number" (it is not a number) but it is not clear to me 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 a logical level that the 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:

var a = 1/"lunes"; //NaN
var b = Math.sqrt(-1) //NaN

Both a and b result in NaN . Now, is it correct that they are the same?

This is why the isNaN() function is used to verify if we are dealing with a NaN or not instead of trying to compare it against another NaN .

This does not apply to undefined because it has a precise meaning: An undefined identifier. On the other hand, NaN is a kind of invalid value for what in other languages ​​would be a runtime error or exception.

Scroll to Top