0

So recently i was studying for my interview, I came accross shallow copy and deep copy in javascript, I read some blogs and understood that it can be a huge problem. So i started to learn how to identify them, everything was going great until this example came

In this example, members array contains the original person object after setting it null

let person = {name : "Lydia"};
const members = [person];
person = null;

console.log(members);

But here when I do this

let person = {name : "Lydia"};
const members = [person];
person.name = null;

console.log(members);

The member array no longer contains the original object.

Please explain why this is happening, would appreciate any examples and reading material around this, thanks

  • 2
    “ The member array no longer contains the original object” — Incorrect. It does contain the original object. You just modified the original object. – Quentin Jul 11 '23 at 06:00
  • 1
    `members` is created with the `reference` of the person object. So, if you update `person` object, the change will appear in all the places where it is referenced. Thus you see `person.name` as `null` in `members` after the change. Here, you are not doing any copying. You are referencing. If you want to make a copy, do this `members = [{...person}]`. This makes a shallow copy. If you want to make a deep copy, `members = [structuredClone(person)]`. But, in this case, both copies can be considered as deep copy, as `person` object only has primitive values. – Tamil Vendhan Kanagarasu Jul 11 '23 at 06:25
  • 1
    If `person` has an `address` field, which is an object, then you will see the difference between `shallow copy` and `deep copy` – Tamil Vendhan Kanagarasu Jul 11 '23 at 06:25

0 Answers0