Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete property from shallow copied object

If I have one object, and shallow copy of it. For example:

var person = {
  name: "Foo",
  age: 10,
  child: {
    name: "Matrix"
  }
}

var copiedPerson = {...person}
console.log(person, copiedPerson);

If I change person.name = "NewName";, copedPerson will stay intact.

If I change person.age = 8;, copiedPerson will stay intact.

But if I change person.child.name = "Neo";, copiedPerson.name will also through reference to point also to same name "Neo".

Everything about that is clear to me.

But I do not understand, why when I delete person.child;, nothing happens to copiedPerson.child;

In my logic cause both of them changes when I change one of them, now I also expected when one of them is deleted that other one should also be deleted. (Cause they references to same location in memory)

Can someone explain me why this didn't happen and which part I misunderstood?

like image 204
Predrag Davidovic Avatar asked Feb 05 '26 05:02

Predrag Davidovic


1 Answers

There is a little gap in the mental model you're having about the references right now. So essentially, you understand that if you change the nested object person.child.name the value in the copiedPerson.child.name would change too.

But at the end of the day, the child property is only containing the reference of the nested object for both person and the copiedPerson objects.

So, when you delete it from the original person object, you're deleting the reference of this nested object from the person's child property but this nested object still remains in the memory

Hence, the reference contained in the copiedPerson.child still remains untouched and can access this object saved in the memory

like image 64
d_bhatnagar Avatar answered Feb 07 '26 21:02

d_bhatnagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!