Why isn't this object being passed by reference when assigning something else to it?

Dev555 picture Dev555 · Feb 24, 2012 · Viewed 17.5k times · Source

I know that in JS, objects are passed by reference, for example:

function test(obj) {
    obj.name = 'new name';
}

var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // new name

But why doesn't the below work:

function test(obj) {
    obj = {};
}

var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // foo

I have set the object to {} (empty) but it still says foo.

Can any one explain the logic behind this?

Answer

Alexander Varwijk picture Alexander Varwijk · Feb 24, 2012

If you are familiar with pointers, that's an analogy you can take. You're actually passing a pointer, so obj.someProperty would dereference to that property and actually override that, while merely overriding obj would kill off the pointer and not overwrite the object.