Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, is chained assignment okay?

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?

like image 214
JamieJag Avatar asked Aug 02 '10 11:08

JamieJag


People also ask

What is chained assignment?

Chained assignments are used as a shortcut when you want to bind several variables to the same value. Copy x = y = somefunction() which is the same as this: Copy y = somefunction() x = y. Note that the preceding statements may not be the same as.

Does JavaScript have multiple assignment?

“JavaScript allows multiple left-hand assignments” Well, if you're not familiar, in JavaScript you can write the variable assignment expressions like this. var a = b = c = d = 10; The assignment expressions are always evaluated from right-to-left.

How does assignment work in JavaScript?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.


1 Answers

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 [] 
like image 155
Tim Down Avatar answered Sep 20 '22 06:09

Tim Down