80

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

> undefined === undefined
true
> NaN === NaN
false
> a = NaN
NaN
> a === a
false

On the documentation page I see this:

Testing against NaN

Equality operator (== and ===) cannot be used to test a value against NaN. Use isNaN instead.

Is there any reference that answers to the question? It would be welcome.

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

3 Answers3

71

Strict answer: Because the JS spec says so:

  • If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.

Useful answer: The IEEE 754 spec for floating-point numbers (which is used by all languages for floating-point) says that NaNs are never equal.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    Also, it's part of the axioms that define natural numbers. Check out the second bullet: https://en.wikipedia.org/wiki/Peano_axioms#Formulation – Loupax Apr 19 '16 at 10:51
  • @Loupax How does that relate? NaN is not a natural number. It's not a number? Is there a joke here I'm not getting? – Grant Gryczan Jan 01 '21 at 22:58
  • 1
    @GrantGryczan I don't even remember what I had in mind back then. Now I just think of this as "Just because the NaNs beside the equality operator are not numbers, it doesn't mean they are the same non number" and just leave it at that – Loupax Jan 28 '21 at 18:47
  • JavaScript automatic type conversion convert `NaN` into number, so checking if a number is not a number will always b `false`. and `NaN !== NaN` will be true. – Aamer Shahzad Feb 26 '21 at 11:15
14

This behaviour is specified by the IEEE-754 standard (which the JavaScript spec follows in this respect).

For an extended discussion, see What is the rationale for all comparisons returning false for IEEE754 NaN values?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.

you may find a details rules in here-

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Md Mehedi Hasan
  • 1,733
  • 1
  • 21
  • 34