Why does Nan === Nan return false in Javascript?

Asked

Viewed 60 times

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.

  • 1

    It has nothing to do with Javascript directly, this behavior comes from the technical standard of floating point numbers (IEEE 754)

  • 2

    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.

  • 1

    It’s weird, right?! That’s why typeof NaN is 'number' and null === null is true, despite typeof null was 'object' and {} === {} was false.

  • 3

    @Cmtecardeal, all of it null is the "same" object, there gives true. The two literal objects there are different, so return false, but if you do let a = {}; a === a;, will have true. What about the NaN cannot be comparable, it is not really about the type, but about its very existence and the consequences of that. See more here.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.