0

I got this simple piece of code:

var x=10;
var y=8;
 x -= y += 9;


alert(x+" and "+y);

The result will be "-7 and 17".

Why does JavaScript executes the y +=9 before the x -= y?

5
  • 6
    Because -= and += are right associative operators and this are evaluated right-to-left. Commented Dec 26, 2019 at 8:49
  • You can check the order on astexplorer.net. Expand the expression on the right side panel to see the order Commented Dec 26, 2019 at 8:50
  • 1
    @vlaz stop answering in the comments! ;) Commented Dec 26, 2019 at 9:21
  • @JonasWilms is there not a canonical for all things to do with precedence? I don't want to answer this question then find out somebody asked a different one that is still simply "how are operators evaluated". Commented Dec 26, 2019 at 9:23
  • 1
    @vlaz not that I know of ... And you already gave a good answer (as a comment), so there would be no harm from posting that as an answer. (with the positive side effect that you get closer to a js gold badge, and I no longer have to dupe hammer your suggestions ;)) Commented Dec 26, 2019 at 9:25

1 Answer 1

1

Operator precedence determines the way in which operators are parsed with respect to each other. Operators with higher precedence become the operands of operators with lower precedence

Associativity determines the way in which operators of the same precedence are parsed.

Since -= and += are right associative therefore they are evaluated from right to left.

Hence y +=9 gets evaluated first.

Reference Link for operators

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.