3

Someone can explain me in the following code, why when I do o = {}, the object is not being reset?

var funky = function (o) {
    o.z = null;
    o.a = "aaa";        
    o = {};
};

var x = { z: "zzz"};
funky(x);

console.log(x);
Sebastian Pederiva
  • 381
  • 2
  • 4
  • 16

2 Answers2

7

Because JavaScript doesn't pass by reference. It passes references by value.

The difference is subtle, but important. The gist of it is, the value of an object variable isn't an object; it is a reference to an object. Passing a variable passes a copy of that reference. With it you can modify the content of the object virtually at will, but you couldn't replace it with a whole other object in a way the caller could see.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • Is there no way to pass by reference? – Ash Burlaczenko Mar 14 '13 at 15:08
  • 3
    You can "simulate" pass by reference by passing in an object and modifying the object. However you can't reassign the object. Think of it as passing in a pointer to a mutable object. You can modify the object through the pointer's members, but you cannot reassign the pointer and expect the outside function to take the modified pointer. – anthony sottile Mar 14 '13 at 15:09
2

o is just an alias to whatever it's currently pointing, it's not the instance (pass by value).

If you want to emulate "pass by reference", you can do it:

var x = { ... };
var container = { x: x };
funky(container);

Now you can reset it in funky():

container.x = {};
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • You can't modify the object created with `var x = ...` inside your function. `o = {};` doesn't modify the existing object, it creates a new one. `o` now points to the new object but there is no way to change `x`. So what you need is to put `x` into another object. – Aaron Digulla Mar 21 '13 at 13:53