Vehbi Karaağaç
Vehbi Karaağaç

Reputation: 99

Why is foo object not changing?

var foo = {'bar': 1};

function overwriteFoo(obj) {
   obj = foo;
   obj = {'bar': 2};
}

overwriteFoo(foo)
console.log(foo)

I thought that assigning foo to obj would make this work how I wanted. I thought that objects in javascript were sent by reference so why cant I reassign foo?

Upvotes: 0

Views: 37

Answers (2)

spadletskys
spadletskys

Reputation: 125

Assining a variable to another variable just returns the assigned variable's content.

Example:

var obj1 = {hello: 'hello'};
var obj2 = obj1;

alert(obj2);// will return hello: 'hello'

// BUt if you try to change obj2 to an object then obj1 will be just unassigned from obj2 but is not changed.

Upvotes: 0

Aplet123
Aplet123

Reputation: 35512

As some people say, everything is pass-by-value, and objects' values are their reference. When you do obj = {'bar': 2}, you are reassigning obj to point to {'bar': 2} instead of pointing to foo. In fact, there is no way to just swap out an entire object like that. You can, however, change properties, as they essentially "dereference" the value:

function overwriteFoo(obj) {
    obj.bar = 2;
}
overwriteFoo(foo);
console.log(foo); // will now be {bar: 2}

Upvotes: 1

Related Questions