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"}
3 Answers 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
Comments
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'.
Comments
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.
user = null;does not modify the object{ name: 'John' }but the reference of what the variableuserpoints to.