3

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?

http://jsfiddle.net/8EWG4/

asked Oct 29, 2011 at 17:30
1
  • I'm guessing this has to do with NaN being 'falsey'. Commented Oct 29, 2011 at 17:34

4 Answers 4

5

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().

answered Oct 29, 2011 at 17:38
Sign up to request clarification or add additional context in comments.

1 Comment

You can actually use that property as a way of checking for NaN - if x !== x yields true, then x must be NaN.
3

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

answered Oct 29, 2011 at 17:35

Comments

2

To evaluate a variable is NaN ( not a number ), consider using isNaN(number) . It will give you correct answer.

answered Oct 29, 2011 at 17:34

Comments

2

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.

answered Oct 29, 2011 at 17:35

2 Comments

Then why does alert("" == false); evaluate to true?
@Oliver Weiler: That's also in the specification. == should call ToNumber on both arguments in case of a string and a boolean, and ToNumber returns 0 for both "" and false.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.