JavaScript object reference


In JavaScript, what happens when a new variable is assigned to an existing object? Does that create a copy of the original object?

Well, let’s see:

var original = { id: 1 };
var copy = original;

copy.id = 2;

console.log(copy.id);     // 2
console.log(original.id); // 2

In the example, copy ended up overriding original. So it turns out that instead of making a copy, it makes a reference to the object.

Now what if the original variable is reassigned to a different value?

var obj = { foo: 'bar' };
var ref = obj;

obj = null;

console.log(obj); // null
console.log(ref); // { foo: 'bar' }

In this case, obj being reassigned to null doesn’t change ref because ref continues to point to the original reference.

This is why an empty object does not equal another empty object—the references simply don’t match.

var obj1 = {};
var obj2 = {};
obj1 === obj2; // false
{} === {};     // false

It’s only equivalent when an object is compared to its own reference.

var obj = {};
var ref = obj;
ref === obj; // true

Check out this MDN article for more information.



Please support this site and join our Discord!