2
var foo=[0];
if(foo) alert('first');
if(foo==true) alert('second');

Tell me please, why the second alert doesn't work? In first alert foo casts to Boolean, so

Boolean(foo);
//true

If "foo" is "true", why doesn't the second alert work?

1
  • Since when is an Array equal to true? Commented Mar 16, 2011 at 10:51

3 Answers 3

5

Here,

if( foo) alerts because foo isn't null and the condition evaluates to true.

However, this doesn't mean that foo itself is equal to true, hence the second alert doesn't show.

Sign up to request clarification or add additional context in comments.

Comments

1

Because initially foo is an Array, not a Boolean and you are comparing foo to a boolean value. The if (...)-statement evaluates to true or false and foo == true evaluates to false here. If you used if (!!foo == true) (or just if (!!foo)) or if (foo != null) or if (foo) the second alert would have fired.

Comments

1

Because there's a difference between the conversion of foo to boolean (which works for an Array) and the comparison of foo to true.

In the latter case, it's a comparison without a conversion, and foo clearly is not the same as true. Note that a conversion does still take place: foo == true is false which is finally "converted" to false for the if. :)

7 Comments

There is a special operator "compare with type check" === in JS and PHP. So operator "==" makes comparison WITH type casting.
@Scalar: I like how you're trying to teach me something that directly contradicts the behaviour you've observed that you asked for help on in the first place.
@Tomalak Geret'kal: Sorry, may be i don't understand you, cause my English is not very good :-[ I thougth that you dont see difference between "==" and "===". My first question is the last thing i don't understand in JS type system.
=== is the strict equal operator and only returns a Boolean true if both the operands are equal and of the same type. == is the equal operator and returns a boolean true if both the operands are equal... which they're still not.
But, for example [1]==true;//true, wow! and [0]==true;//false and [0]==false;//true, but [2]==true;//false and [2]==false;//false. I understand how it works, now, when i read ECMA-262 (ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf), but i still don't understand algorithm of if statement expression check.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.