Is the order of execution of operations in Javascript guaranteed to be the same at all times?

淺唱寂寞╮ 提交于 2021-02-04 18:17:28

问题


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 returned value between (A) and (B) is explained by the value of x at the time it becomes evaluated. I figure that backstage something like this should happen:

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

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

So, I have a few questions about this,

Is this guaranteed to be true for all Javascript implementations?

Is it defined to be this way by the standard?

Or, is this some kind of undefined behavior in Javascript world?

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

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

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


回答1:


Is this guaranteed to be true for all Javascript implementations?

Yes.

Is it defined to be this way by the standard?

Yes, you can read it yourself here.

Specifically, the runtime semantics: evaluation of the addition operator (+) specify that the left expression is evaluated before the right expression.

It's the same for the evaluation of argument lists.

Or, is this some kind of undefined behavior in Javascript world?

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



来源:https://stackoverflow.com/questions/35382317/is-the-order-of-execution-of-operations-in-javascript-guaranteed-to-be-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!