Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complicated javascript conditional expression

What is the correct way to interpret this complicated javascript expression?

some_condition ? a = b : c = d = e;

Following operator precedence rules, I would expect it to be:

(some_condition ? a = b : c) = d = e;

But it seems that the grouping is actually:

EDIT: (The original grouping was unclear. See below for update)

EDIT: some_condition ? a = b : (c = d = e);

Why is this so? (And no I did not write that code)

EDIT: This seems to suggest that in Javascript to say ?: have higher precedence than = is not entirely true. As a further example:

x = y ? a = b : c = d = e;

If ?: have higher precedence than = (as in C) then the grouping would be

x = ((y ? a = b : c) = (d = e));

but rather (from the answers) what we have is

x = (y ? a = b : (c = d = e));

The relative precedence of ?: and = seems to depend on where they appear in the expression

like image 234
tyty Avatar asked Apr 02 '12 15:04

tyty


2 Answers

If you look at javascript precedence operators, assignments have a lower precedence than conditional operator but, according to ecmascript specs, Par. 11.12

11.12 Conditional Operator ( ? : )     
Syntax

ConditionalExpression : LogicalORExpression  
       LogicalORExpression ? AssignmentExpression : AssignmentExpression

AssignmentExpression is evaluated as follows:  
1.  Let lref be the result of evaluating LogicalORExpression.   
2.  If ToBoolean(GetValue(lref)) is true, then  
   a. Let trueRef be the result of evaluating the first AssignmentExpression.   
   b. Return GetValue(trueRef).  
...

So the conditional operator evaluates that code grouping every assignment expression and it works as everybody explained.

Maybe I could be wrong here, but I think that operators precedence are related instead to how js parse an expression like

a = (b < c)? b : c;

(and not when contained in the AssignmentExpressions) where in this scenario the assignment should have a lower precedence, so Javascript evaluates the whole statement as

a = ((b < c)? b : c);
like image 96
Fabrizio Calderan Avatar answered Sep 28 '22 13:09

Fabrizio Calderan


Thats an abbreviated if else statement

the long form would be

if(some condition)
{
 a = b;
}
else 
{
 c = d = e;
}
like image 36
Simon West Avatar answered Sep 28 '22 12:09

Simon West