Nagendra Kamath
Nagendra Kamath

Reputation: 31

Javascript copies objects by reference. But the below code I assigned one object with null. But the other object still has the same value

Here there are two objects, user and user1. The user is copied to user1. The user is then assigned to null, but the user1 does not change.

let user = {
    name : 'Nagendra Kamath',
    age : 22,
    goodMorn(){
        console.log('Good Morning '+ this.name);
    }
};

let user1 = user;

user = null; 


user1.goodMorn(); // even if we have assigned user to null the value of user1 remains same
user.goodMorn();  // throws an error

Please tell me how is this possible??

Upvotes: 1

Views: 38

Answers (1)

qiAlex
qiAlex

Reputation: 4346

Here you create an Object that exist in memory, and reference user to this object.

let user = {
    name : 'Nagendra Kamath',
    age : 22,
    goodMorn(){
        console.log('Good Morning '+ this.name);
    }
};

Now you assign a new reference user1 to the same Object.

let user1 = user;

Now you assign to user value null

user = null;

But the Object is still exist, and reference user1 to the object also exist, so it's fine that

user1.goodMorn(); // works, because it's still a reference to the object.
user.goodMorn();  // throws an error, because it's value is null

Important thing here: user1 is not a reference to user, because user is also a reference. user1 is a reference to the original Object in memory, user1 is the similar reference as reference user

Upvotes: 1

Related Questions