views:

86

answers:

4

Am not new to JS or its syntax, but sometimes, the semantics of the language has me stumped at times. At work today, a colleague mentioned this:

var a = b = [];

is not the same as

var a = [], b = [];

or

var a = []; var b = [];

since the first version actually assigns the reference to an empty array to a and b. I couldn't quite accept this as true, but I'm not sure. What do you all think?

+3  A: 

Your colleague is right. The first statement creates a new, empty array. Then, a reference to this array is assigned to b. Then, the same reference (which is the result of the assignment expression) is assigned to a. So a and b refer to the same array.

In all other cases, you create two individual arrays.

By the way: This behavior is quite common and is the same in all C based programming languages. So this is not JavaScript specific.

Tobias Haustein
Thanks for your reply, Tobias, and also for pointing out the commonality in all C-based languages.
JamieJag
+1  A: 

Your colleague is right:

var a = b = [];
a.push('something');
console.log(b);          // outputs ["something"]

but:

var a = [], b = [];
a.push('something');
console.log(b);          // outputs []
Daniel Vassallo
+6  A: 

Yes, they're not the same. var a = b = [] is equivalent to

var a;
b = [];
a = b;

Not only do both a and b get assigned the same value (a reference to an empty array), b is not declared at all, which means that it is silently created as a property of the global object and acts similarly to a global variable, wherever the code is, even inside a function. Which is not good.

You can see this quite easily:

(function() {
    var a = b = [];
})();

window.console.log(b); // Shows []
Tim Down
I didn't see immediately about b being a global variable, thanks!
JamieJag
+1 Another reason to avoid an assignment to an unresolvable reference is that on ES5, under strict mode, a `ReferenceError` will be thrown.
CMS
+1  A: 

With the first example b is a reference to a, and b becomes a global variable, accessible from anywhere (and it replaces any b variable that may already exist in the global scope).

Fabien Ménager