Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does operator precedence works other way with variable assignment in Javascript

I have a code like this.

let y = 2;
y *= 3+4;

The above line is a short hand of y = y*3+4. So as per the precedence level, * should take a precedence. So i am expecting a calculation like this, (2*3)+4 so that should return 10. But why does it executes this way 2*(3+4) and returned 14. Can somebody explain in detail?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s helpful to see how the JS parser interprets that statement: https://esprima.org/demo/parse.html?code=y%20*%3D%203%2B4

Binary expressions are evaluated before assignment expressions.

The + is a binary expression that has 3 and 4 as operands.

The *= is an assignment expression that has, on the left hand side, y, and on the right hand side, the result of the binary expression (3 + 4, or 7).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading