Javascript operator precedence 5-4+2*3

From the documentation, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence, it appears that the order of operator precedence is *, +, -, etc (highest to lowest).

Though when I tried evaluating 5-4+2*3 , I got 7 as an answer in the console.

This meant the operation was evaluated in this way (5-4)+(2*3) to give 7.

Yet I expected the operation to be evaluated in this way 5-(4+(2*3)) to give -5

My main question is how come it appears that subtraction was evaluated first BEFORE addition to give 7. Yet it should be the opposite.

Am aware that I can use brackets to dictate the order of evaluation. I just wonder why this is happening the way it is.

It is because of the level of precedence. + and - have the same level of precedence and then proceed to read from left to right.

Now here the following actually happened

5-4 + 2 * 3 (Multiply 2 * 3)
5-4 + 6 (Subtract 5-4)
1 + 6 (1 + 6 is added)

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

4 Likes

Oooh I see now. I actually hadn’t realized that:

  1. -,+ have the same level of precedence and are evaluated from left to right.
  2. *, / , % also have the same level of precedence and are evaluated from left to right.

Thank you so much for the clarification.

1 Like