1

Just for fun I was trying to compare a value which I set to NaN to another value which I also set to NaN.

Why are two variables, with identical values, not equivalent?

var a = Number.Nan
var b = Number.Nan
a === b
false

a == b
false

var a = NaN
var b = NaN
a === b 
false
a == b
false

Why does this happen?

kschmit90
  • 378
  • 2
  • 3
  • 13
  • 4
    NaN is not equal to anything including NaN itself. http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 – dfsq Apr 09 '15 at 20:59
  • Note: Going forward (ES6+ or [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Browser_compatibility)), you'll be able to compare `NaN` values using [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). – Jonathan Lonowski Apr 09 '15 at 21:07
  • Even weirder, `a == a` returns false :) – simpleManderson Apr 09 '15 at 21:07

3 Answers3

2

As @TechnicalChaos said, but here are links to MDN over W3Schools ;)

NaN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

IsNaN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

The pertinent parts being:

It is rather rare to use NaN in a program. It is the returned value when Math functions fail (Math.sqrt(-1)) or when a function trying to parse a number fails (parseInt("blabla")).

And:

Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.

Don't think of NaN along the same lines as null or undefined, it's a "special case" :P

But if you're willing to risk it for a biscuit:

NaN.toString() === NaN.toString()
true

But don't do that!

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
1

NaN is Not a Number, there is no evaluated numberic value to compare - Use IsNaN() To compare NaN values. W3 Schools link

TechnicalChaos
  • 452
  • 3
  • 21
-1

Keep in mind that a lot of JavaScript isn't great. It was designed in 10 days and a lot (not all) of it may not be intuitive. This is one of those times where you don't think about why and you just use isNaN(someVar) to check for it.

Brian Schermerhorn
  • 1,361
  • 1
  • 15
  • 22
  • 1
    This isn't a Javascript ideosynchracy, it's part of the IEEE standard for floating point. – Barmar Apr 09 '15 at 21:12
  • If Brian has said "Keep in mind that some of JavaScript is weird", I'd agree: `{} + {} // NaN`, `[] + []; // ""` and the best one `[] + {}; // [object Object]` :P – Adrian Lynch Apr 09 '15 at 21:16