Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 742
Ale Morales Avatar asked Feb 13 '16 16:02

Ale Morales


People also ask

Does JavaScript execute in order?

JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.

Which function is executed first in JavaScript?

Whenever the JavaScript engine receives a script file, it first creates a default Execution Context known as the Global Execution Context (GEC) . The GEC is the base/default Execution Context where all JavaScript code that is not inside of a function gets executed.

How do I run a one by one function in JavaScript?

How can I call them one by one so step2(); is called after step1(); is finished and step3(); is called after step2(); is finished. Step1() is executing a json and appends details to html, Step2() is executing another json and appends info in the divs created by Step1() and Step3() simply hides a loading animation.


1 Answers

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.

like image 181
Bergi Avatar answered Oct 19 '22 08:10

Bergi