Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which order are variables assigned in Javascript?

Apparently this is identical in my Firebug console:

var x = "A", y = x;
x + y === "AA";

and

var x = y, y = "A";
x + y === "AA";

Is this standard ECMAScript behaviour, that the order doesn't play a role in comma-separated var assignments?

Edit: The "mystery" is solved. I tested the first example first, then cleared the console and ran the second. However, at this time, y and x were already defined. If you run the JSFiddle provided by David Thomas you always get an "undefinedA". Case settled.

like image 802
Boldewyn Avatar asked Aug 11 '11 19:08

Boldewyn


1 Answers

var x = y; will raise an exception if y is not defined.

However, the window object is the default context for Javascript interpreters embedded in browsers. If you previously issued:

y = "A";

Then you actually assigned "A" to window.y, therefore var x = y; becomes valid and assigns window.y to x.

like image 147
Frédéric Hamidi Avatar answered Oct 14 '22 19:10

Frédéric Hamidi