10

I am wondering why undefined == undefined but NaN != NaN.

Lenar Hoyt
  • 5,971
  • 6
  • 49
  • 59

5 Answers5

11

Because that's how it is defined in both the Abstract Equality Comparison Algorithm, and the Strict Equality Comparison Algorithm.

If either operand to == or === is NaN, it returns false.

Abstract

  • If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.
    • If x is the same Number value as y, return true.
    • If x is +0 and y is −0, return true.
    • If x is −0 and y is +0, return true.
    • Return false.

EDIT: The motivation for the unequal comparison as noted by @CMS is compliance with the IEEE 754 standard.

From the Wikipedia link provided in the comment below:

...The normal comparison operations however treat NaNs as unordered and compare −0 and +0 as equal. The totalOrder predicate will order these cases, and it also distinguishes between different representations of NaNs and between the same decimal floating point number encoded in different ways.

Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 2
    And it is defined in this way, in the two Equality Algorithms just because the specification is conforming with the rules of the [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754) Standard for the Number type. – Christian C. Salvadó Aug 24 '11 at 16:03
  • 1
    Thanks @CMS. I'll update my answer with the information you provided. – user113716 Aug 24 '11 at 16:08
4

Because Math.sqrt(-5) !== Math.sqrt(-6).

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
2

Not sure why it is like this, but in order to check if a certain statement or variable is a NaN, you should use the isNaN method

sternr
  • 6,216
  • 9
  • 39
  • 63
0

I would assume because the IEEE standard allows for more than one representation of NaN. Not all NaNs are equal to each other...

Brian Knoblauch
  • 20,639
  • 15
  • 57
  • 92
  • According to the ECMAScript spec, all NaN values are indistinguishable from each other (although admittedly, implementations can differ): http://es5.github.com/#x8.5 – James Allardice Aug 24 '11 at 15:40
  • I don't believe that being indistinguishable is enough to establish equality. Any logicians on here know for sure? – Brian Knoblauch Aug 24 '11 at 15:42
  • 2
    It's the opposite: Being able to be equal to some but not others would make them distinguishable. Either they must all be equal or they must all by unequal if they are to be indistinguishable. – Chuck Aug 24 '11 at 15:48
-1

The reasoning is that the creators wanted x == x returning false to mean that x is NaN, so NaN == NaN has to return false to be consistent.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171