-1
let user = {
  name: "John",
  age: 30,
  sayHi() {
    alert( this.name ); 
  }
};
let admin = user;
user = null; // overwrite to make things obvious
admin.sayHi(); // John

Here user variable should be a reference type variable and not primitive. So when we assign user variable to admin varaiable so we are not deeply coping the user variable. Therefore both should point to the same location in the heap memory.

So when we assign user = null. So admin variable should also be equal to null since they both should point to the same location in heap memory.

But still admin object is able to access sayHi() method. Can anyone please explain why?

  • 1
    no, you said user=null, not admin = null - you've assigned a new value to user, you have not touched admin at all after assigning it to the same object that was user – Bravo Apr 17 '22 at 07:53
  • or ... put it another way ... there's an `object`, it is `{ name: ...}` etc ... first, `user` has a reference to it ... then `admin` has a reference to it ... then `user` does not have a reference to it ... you have not made any change to the `object` from when it was defined – Bravo Apr 17 '22 at 07:54
  • @Bravo what if we do user.sayHi = null; so in this case admin.sayHi() will show error right ? Becoz now we are not assigning a new value to user. Therefore both will point to the same heap memory where the value stored will be { name: "John", age: 30, sayHi : null } – Tejas Sawant Apr 17 '22 at 08:05
  • 1
    yes, because you modified the object – Bravo Apr 17 '22 at 08:08

1 Answers1

-1

You will need to look at it this way. The variable is just pointing to an object created during shallow copy. When you assign user to null the object still exists only its reference was changed to null. the admin is still pointing to the reference user was earlier pointing to hence the behviour enter image description here