0

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"}
asked Jan 9, 2019 at 14:52
2
  • user = null; does not modify the object { name: 'John' } but the reference of what the variable user points to. Commented Jan 9, 2019 at 14:55
  • 1
    Also, I'm not sure what this question has to do with garbage collection. Commented Jan 9, 2019 at 14:56

3 Answers 3

3

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
answered Jan 9, 2019 at 15:02
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Jan 9, 2019 at 15:02

Comments

0

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.

answered Jan 9, 2019 at 15:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.