Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's difference multiple blank variables declare

literal object methods:

var objectA = {}; 
var objectB = {};

vs

var objectA = objectB = {};

constructor object methods:

var objectA = new Object();
var objectB = new Object();

vs

var objectA = objectB = new Object();
like image 995
John Yin Avatar asked Jul 03 '26 12:07

John Yin


1 Answers

Actually, when you do

var objectA = {}; 
var objectB = {};

or

var objectA = new Object();
var objectB = new Object();

You are creating two different JavaScript objects and they are referred by objectA and objectB. But when you do

var objectA = objectB = {};

or

var objectA = objectB = new Object();

You are actually creating only one object and making both objectA and objectB refer the same object.

You can confirm this by checking if both the objects are one and the same or not, like this

var objectA = {}, objectB = {};
console.log(objectA === objectB);
// false
var objectC = objectD = {};
console.log(objectC === objectD);
// true

Note:

var objectC = objectD = {};

will be evaluated like this

var objectC = (objectD = {});

That is why both objectC and objectD refer the same object.

Important: As dfsq mentions in the comment, in the last example, objectD will be leaked to the global scope. So, avoid using this pattern.

like image 151
thefourtheye Avatar answered Jul 05 '26 00:07

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!