In this case I found NaN==NaN is false. I don't understand why this is happen because of both type is number and value is same. So how it possible.
-
2I wonder which cases you found when this was true??? – Bergi Jan 27 '15 at 06:58
-
You will probably find `isNaN(num)` useful. See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) for details. – jfriend00 Jan 27 '15 at 06:58
-
try it.... alert(NaN == NaN) will always be false.. Not in some cases, in all... – Nico Jan 27 '15 at 06:59
-
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 Jan 27 '15 at 07:03
4 Answers
Treat this as NaN is UNKNOWN so,
UNKNOWN can never be same as another UNKNOWN....UNKNOWN(NaN)==UNKNOWN(NaN)//false
another example:
Lets say x='a', y='b' both are not numbers so x=NaN, y=NaN but x!=y
http://es5.github.io/#x11.9.6.
http://en.wikipedia.org/wiki/IEEE_floating_point
The IEEE 754 spec for floating-point numbers (which is used by all languages for floating-point) says that NaNs are never equal.
- 2,945
- 1
- 13
- 23
NaN's are never equal to each other by design.
Math.log(-1) is NaN
Math.log(-2) is NaN
does that mean that Math.log(-1) == Math.log(-2)?
- 28,017
- 9
- 48
- 94
NaN's are unusual case. They are not equal to anything (to itself too).
So, it returns false when you test NaN==NaN.
To test the NaN you can use as @Bergi commented:
var x = NaN;
if(x !== x){
console.log('It is NaN');
}
- 78,842
- 31
- 152
- 211
-
I don't think it's just Javascript. I think this is pretty common, and may even be required by IEEE-754. – Barmar Jan 27 '15 at 06:59
Nan - JavaScript what a beautiful case.
Testing against NaN
Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.
NaN === NaN; // false Number.NaN === NaN; // false isNaN(NaN); // true isNaN(Number.NaN); // true
- 669,327
- 51
- 454
- 560
- 2,453
- 2
- 23
- 27