Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  127] [ 4]  / answers: 1 / hits: 18809  / 14 Years ago, mon, august 2, 2010, 12:00:00

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?


More From » object

 Answers
50

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 []

[#96052] Thursday, July 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Thu, Apr 8, 21, 00:00, 3 Years ago
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
;