Is the order of operations in Javascript the same in all cases?

When I do something like this:

var x = 5; console.log( x + (x += 10) ); //(B) LOGS 10, X == 20 console.log( (x += 10) + x ); //(A) LOGS 0, X == 30 

The difference in the return value between (A) and (B) is explained by the value of x at the time of its calculation. I believe something like this should happen behind the curtains:

  TIME ----> (A) (x = 5) + (x += 10 = 15) = 20 (B) (x += 10 == 15) + (x == 15) = 30 

But this is only true if and only if x is evaluated in the same order from left to right that it was written.

So, I have a few questions about this,

Is guaranteed true for all Javascript implementations?

Is it defined in this way as standard?

Or is this some undefined behavior in the Javascript world?

Finally, the same idea can be applied to function calls,

 var x = 5; console.log(x += 5, x += 5, x += 5, x += 5); // LOGS 10, 15, 20, 25 

They are also evaluated in order, but is there a stronger guarantee that this should always happen?

+5
source share
1 answer

Is this guaranteed for all Javascript implementations?

Yes.

Is it defined in this way as standard?

Yes, you can read it yourself here .

In particular, runtime semantics: evaluating the addition operator ( + ) indicates that the left expression is evaluated before the correct expression.

The same goes for evaluating argument lists .

Or is this some undefined behavior in the Javascript world?

Yes, there is undefined behavior in JavaScript, but not here.

+1
source

Source: https://habr.com/ru/post/1242956/


All Articles