doremi
doremi

Reputation: 15329

Multivariable Assignment in Javascript

Can someone explain why if I add a property to foo, somehow bar also inherits that property when I do this:

var foo = bar = {};
foo.hi = 'hi';

console.log(bar); //Object {hi: "hi"}

How does this work? I'm setting properties on foo, not bar. I realized I passed the object to bar and then bar to foo, but I must be missing something here.

Integer assignment works differently and more sense (to me anyhow):

var foo = bar = 5;
foo = 4;

console.log(bar); // 5

Upvotes: 0

Views: 160

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

by doing foo = bar = {};, foo and bar are pointers to same object. so when you do:

foo.hi = 'hi';

It sets bar.hi also, because foo and bar point to the same object. To make it different, you should do:

var foo = {},  bar = {};
foo.hi = 'hi';

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

Objects are passed by reference in JavaScript. Strings and number literals are not. In your code foo === bar, is the same object. You can simply declare the variables separately:

// Two different object instances
var foo = {};
var baz = {};

Upvotes: 1

Related Questions