Pass-by-reference JavaScript objects

When 2 variables are pointing to same object, it doesn't mean that they're now magically 'tied' to each other.

In your case, objTwo = {} is simply changing objTwo to point at the new object you created.


When you evaluate

objTwo = {};

Javascript interprets that as reassigning objTwo to a new literal empty object, and leaves its old value alone.

If you want to remove a key from objOne by reference, you can use the delete keyword:

delete objTwo.x;  // also deletes the x property of objOne

objTwo = {}; doesn't work the way you think it works. I usually recommend thinking of variables as "pointers".

objOne and objTwo are two totally different variables. When you did objTwo = {};, what it did was have the objTwo variable point to another object. It does not alter the objOne variable.

Let's visualize:

var objOne = {
  x: 1,
  y: 2
};

// objOne -> { x: 1, y: 2 }

var objTwo = objOne;

// objOne -> { x: 1, y: 2 } <- objTwo

objTwo.x = 2;

// objOne -> { x: 2, y: 2 } <- objTwo (update object via objTwo variable)

objTwo = {};

// objOne -> { x: 2, y: 2 }, objTwo -> {}

When you assign one variable to another, it's not that both those variables are now linked by reference; you're misunderstanding what "pass by reference" means here.

A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.

When you assign a new value to one of the variables, you're just modifying the value that variable holds. The variable now ceases to hold a reference to the object, and instead holds something else. The other variable still holds its reference to the original object, the assignment didn't influence it at all.

Tags:

Javascript