Search code examples
javascriptoperator-precedenceassignment-operatorconditional-operator

Can someone explain why the conditional operator and the assignment operator behave strangely when used together?


Can someone explain why the below code will not give an error:

var x;
false ? null : x = 1;

According to MDN-operator precedence the conditional operator has a higher operator precedence than the assignment operator, which means that the above code should give an error because it's actually parsed like:

var x;
(false ? null : x) = 1

but it didn't give an error whereas this works as expected:

var x;
x = 1 ? alert(x) : null;

The above code is parsed like:

var x;
x = (1 ? alert(x) : null);

because the conditional operator has a higher precedence, but why in my very first code will it not give an error if the conditional operator has a higher precedence than the assignment operator?


Solution

  • If you look at the actual grammar, the two "branches" of the conditional operator are assignment expressions. Thus,

    false ? null : x = 1;
    

    is parsed as

    false ? (null) : (x = 1);
    

    Because the first expression in a ? : construct is a short-circuit expression in the grammar, the expression

    x = 1 ? alert(x) : null;
    

    is parsed as

    x = (1 ? alert(x) : null);