views:

345

answers:

4
var var1 = 1,
    var2 = 1,
    var3 = 1;

This is equivalent to this:

var var1 = var2 = var3 = 1;

I'm fairly certain this is the order the variables are defined: var3, var2, var1, which would be equivalent to this:

var var3 = 1, var2 = var3, var1 = var2;

Is there any way to confirm this in JavaScript? Using some profiler possibly?

+2  A: 

Try this:

var var1=42;
var var2;

alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.

Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.

It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.

Joel Coehoorn
Damn, beat me to it.
Mike Robinson
Thanks for the answer. I think I was looking for a way to use the alerts while still maintaining the multiple-assignment structure (a=b=c), but I don't think that's possible.
David Calhoun
Individual statements like that in javascript (and, though several expressions, that all works out to a single statement) can be considered atomic. You'd have to break it up.
Joel Coehoorn
A: 

Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;.

If the value of any of these variables is 1 after this statement, then logically it must have started from the right, otherwise the value or var1 and var2 would be undefined.

Although it will not compile, you can think of it as equivalent to var (var1 = (var2 = (var3 = 1))); where the inner-most set of parenthesis is evaluated first.

Justin Johnson
Thanks, this definitely helps. It helps to think in terms of what errors would be thrown if it were evaluated other than right-to-left (in this case, the error would be that var1/var2 are undefined).
David Calhoun
It's actually a syntax error. You can not have `(` immediately after `var`. Removing the outer set of parenthesis allows it to compile without error, `var var1 = (var2 = (var3 = 1));`. At the time I felt that it didn't illustrate the point quite as well, but I suppose its the same.
Justin Johnson
+7  A: 

Actually,

var var1 = 1, var2 = 1, var3 = 1;

is not equivalent to:

var var1 = var2 = var3 = 1;

The difference is in scoping:

function good() {
  var var1 = 1, var2 = 1, var3 = 1;
}

function bad() {
  var var1 = var2 = var3 = 1;
}

good();
alert(window.var2); // undefined

bad();
alert(window.var2); // 1. Aggh!

Actually this shows that assignment are right associative. The bad example is equivalent to:

var var1 = (window.var2 = (window.var3 = 1));
Crescent Fresh
Ooo, good cath.
Justin Johnson
Dang, that's unexpected. Thanks for the tip, I'll watch out for that.
David Calhoun
A: 

Further info can be found here:

Operator Precedence