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);
3
  • Try setting o to null instead. Commented Mar 14, 2013 at 15:09
  • possible duplicate of Pass Variables by Reference in Javascript Commented Mar 14, 2013 at 15:10
  • setting o to null doesn't change anything Commented Mar 14, 2013 at 15:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there no way to pass by reference?
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.
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 = {};

1 Comment

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.
0

There is neither pass-by-value nor pass-by-reference in JavaScript.

Identifier is binding to value. When call funky(x), parameter o is binding to the value of x, which is {z:"zzz"}.

When JavaScript interprets o.z=null and o.a="aaa", it updates the value of x(because it is binding to it).

When JavaScript interprets o = {}, it rebind o to {}. So, the output must be {z:null, a:"aaa"}, which is the value of x.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.