In JavaScript, is chained assignment okay?
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 []
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).
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.
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 the same empty array), b
is not declared at all. In strict mode in ECMAScript 5 and later, this will throw a ReferenceError
; otherwise, unless there is already a variable b
in scope, b
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 = [];
})();
console.log(b); // Shows []