6

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?

Ale Morales
  • 2,728
  • 4
  • 29
  • 42
  • Does this help, or is your question specifically asking about operator execution order only? http://stackoverflow.com/questions/14863430/does-javascript-have-undefined-behaviour – Joachim Isaksson Feb 13 '16 at 16:34
  • I'm asking particularly about guaranteed/predictable execution order. But that was a nice resource, didn't knew about those things. Thanks. – Ale Morales Feb 13 '16 at 16:36
  • 1
    I believe this should clear up any questions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence – Hogan Feb 13 '16 at 16:48
  • Thanks Hogan. Following the syntax from that article, I'm trying to know if, when `(a OP b)` is to be evaluated, I can rely the value in `a` being evaluated/read before `b`. – Ale Morales Feb 13 '16 at 17:06

1 Answers1

2

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375