Given this script:
var number = NaN;
if (!number) {
alert("yes");
}
alert(number == false);
Why does the first expression `!number evaluates to true, while the second expression number == false evaluates to false?
-
I'm guessing this has to do with NaN being 'falsey'.Ivan– Ivan2011年10月29日 17:34:26 +00:00Commented Oct 29, 2011 at 17:34
4 Answers 4
Keep a look in this article: http://www.smashingmagazine.com/2011/05/30/10-oddities-and-secrets-about-javascript/
There's some tricks about javascript, including informations about NaN:
NaN is a Number
You thought null being an object was ridiculous? Try dealing with the idea of NaN — "not a number" — being a number! Moreover, NaN is not considered equal to itself! Does your head hurt yet?
alert(typeof NaN); //alerts 'Number'
alert(NaN === NaN); //evaluates false
In fact NaN is not equal to anything. The only way to confirm that something is NaN is via the function isNaN().
1 Comment
NaN - if x !== x yields true, then x must be NaN.The ECMAScript specification says so:
x == y is defined as (11.9.3):
If x is NaN, return false.
And ! calls ToBoolean (9.2) first (and then returns the opposite):
The result is false if the argument is +0, −0, or NaN; otherwise the result is true
Comments
To evaluate a variable is NaN ( not a number ), consider using isNaN(number) . It will give you correct answer.
Comments
From wikipedia - JavaScript syntax, boolean:
When used in a logical context, 0, -0, null, NaN, undefined, and the empty string ("") evaluate as false due to automatic type coercion.
!NaN == true
So, as NaN is coerced to false, !NaN evaluates to true.
However, NaN is not equal to false - it is a different type/value.
2 Comments
alert("" == false); evaluate to true?== should call ToNumber on both arguments in case of a string and a boolean, and ToNumber returns 0 for both "" and false.