JavaScript Operator Precedence, Assignment, and Increment?

60 Views Asked by At

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?

1

There are 1 best solutions below

1
Konrad On BEST ANSWER

Summary of the discussion in comments:

Simplified example:

let i = 1
let j = i += 3 + ++i;
console.log(j); //prints 6

i += 3 + ++i is the same as i += (3 + ++i) and not (i += 3) + (++i)

In the ECMAScript specification we can read that left-hand side expression is evaluated first

  1. Let lref be ? Evaluation of LeftHandSideExpression.

Then after right-hand side calculations in step 7

  1. Let r be ? ApplyStringOrNumericBinaryOperator(lval, opText, rval).

So i += (3 + ++i) is really:

let lhs = i // 1
let rhs = 3 + ++i // 3 + 2
i = lhs + rhs // 6

or in thee example from the question:

let lhs = i // 3
let rhs = 3 + ++i // 3 + 4
i = lhs + rhs // 10