In JavaScript (JS), ++ has higher precedence than += or =. In trying to better understand operator execution order in JS, I'm hoping to see why the following code snippet results in 30 being printed?
let i = 1
let j = (i+=2) * (i+=3 + ++i);
console.log(j); //prints 30
Naively, it seems like the i+=2 is executing first, resulting in 3 * (i+=3 + ++i), and then 3 is being used as the starting value for i for both the i+=3 and ++i (resulting in 3 * (6 + 4)). But I'm wondering, if that is the case, why either the ++i or i+=3 is not having its side effect in assigning to i occur before the other executes?
Summary of the discussion in comments:
Simplified example:
i += 3 + ++iis the same asi += (3 + ++i)and not(i += 3) + (++i)In the ECMAScript specification we can read that left-hand side expression is evaluated first
Then after right-hand side calculations in step
7So
i += (3 + ++i)is really:or in thee example from the question: