tags:

views:

62

answers:

1
var c = false;
if(c=[] && c.length==0)alert('hi');

hi is not alerted because c is still false when it executes the second operand of &&, can someone explain how the boolean operands in if condition are executed and in what order?

+3  A: 

I believe this is just a precedence issue - && is binding tighter than =. Your code is equivalent to:

if (c = ([] && c.length == 0))
{
    alert('hi');
}

So it's assigning c the value false rather than the empty array.

Try this instead:

if ((c = []) && c.length == 0)
{
    alert('hi');
}

EDIT: To address Tryptich's comment - I did try this before posting :) As CMS said, an empty array is considered true. Try this:

if (c = [])
{
    alert('empty array is true');
}

or even just this:

if ([])
{
    alert('empty array is true');
}

I checked the spec before posting - I was somewhat surprised that an empty array is considered true, but it is...

Jon Skeet
The alert still wouldn't run in your second example, because in Javascript an empty array is a false-like value. (`[]==false`) is true.
Triptych
Triptych: An empty Array is not considered a false-like value, your example is a *quirk* of the equals operator, try: `!![] == true;`, `![] == false;`, `[] == false;`
CMS
Good edit Jon, BTW *everything* except, `undefined`, `null`, `NaN`, `0`, an empty-string (and of course `false`) evaluate to `true` in a boolean expression.
CMS