Search code examples
javascriptobjectecmascript-5

Javascript - Effect of assigning empty object


JavaScript Learner - please help understand ,

In the below JS snippet, when a "nickname" property is added to object person1, it reflects in Person object as well.

But, when person1 is set to an empty object {} , please help understand why it does not affect person object?


var person  = {
  "firstname" : "Tony",
  "lastname" : "Stark"
};

var person1 = person;

person1.nickname = "Ironman";

console.log(person); 
//Object { firstname: "Tony", lastname: "Stark", nickname: "Ironman" }
console.log(person1);
//Object { firstname: "Tony", lastname: "Stark", nickname: "Ironman" }  

person1 = {};

console.log(person);
//Object { firstname: "Tony", lastname: "Stark", nickname: "Ironman" }  
console.log(person1);
//Object {  }

Thanks in advance!!


Solution

  • In the below JS snippet, when a "nickname" property is added to object person1, it reflects in Person object as well.

    You do person1 = person so, now both variables point to the same memory address so varying one will reflect in the other too.

    But, when person1 is set to an empty object {} , please help understand why it does not affect person object?

    By doing person1 = {}, you're assigning it a new memory address so person and person1 are now two different entities and changing one will not affect the other.