Reputation: 1308
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?
Upvotes: 2
Views: 293
Reputation: 1503140
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...
Upvotes: 3