user3162865
user3162865

Reputation:

Why does JavaScript garbage colection work like this if objects are copied by reference?

If for instance we copy an object like this and modify a property in our copied object:

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference

Why does:

let user = { name: 'John' };
let admin = user;
user = null;
console.log(user); // will return null
console.log(admin);// will return {name: "John"}

Upvotes: 0

Views: 38

Answers (3)

dquijada
dquijada

Reputation: 1699

First of all: that is not garbage collection, but I will not dwell on that since that's not your actual question.

In memory the space occupied by the object { name: 'John' } is still storing that.

You just assigned null to one of the variables "pointing to it".

Imagine it as pointers like in c++:

let user = { name: 'John' };

 user ⟶ {name: 'John'}

admin    

let admin = user;

 user ⟶ {name: 'John'}
       ↗
admin 

user = null;

 user    {name: 'John'}
       ↗
admin 

And therefore "user" isn't really pointing to anything, it's pointing to the 'null' point that basically means 'nothing'.

Upvotes: 1

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15851

There is a heavy misunderstanding on how javascript works

with

let admin = user;

you are referencing user in admin var, not cloning it at all.

Upvotes: 0

JoannaFalkowska
JoannaFalkowska

Reputation: 3677

By calling user = null, you're destroying the reference that the existing Object had to the variable called user, not the actual Object.

You'll be able to use the Object as long as there exists some reference to it. When there is no more references, it'll be garbage collected eventually.

Visualisation of what you did:

user --> { name: 'John' }

user --> { name: 'John' } <-- admin

user --> null
         { name: 'John' } <-- admin

Upvotes: 3

Related Questions