1

Shallow copy is nothing but when trying to copy and change the contents of copied array {array containing objects and not primitive data types} the contents of the original array also got changed.

In the following case, why the dst[0]= {name : "tom"} is a deep copy and not a shallow copy (the contents of the original array "src" is not changed). On the contrary, the second operation which is dst[0].name= "tom" is creating a shallow copy as expected and changing the contents of src. Can someone please clarify this?

let src = [{
  name: 'brat'
}, {
  age: 40
}]
let dst = [...src]


// dst[0]={name:"tom"} 
dst[0].name = "tom";


console.log(`src ${JSON.stringify(src)}`)
console.log(`dst ${JSON.stringify(dst)}`)

0

2 Answers 2

2

That is because in the below line, you are not changing the copied property of src, instead you are re-assigning both 'key' and 'value' and replacing the old property altogether with a new property.

dst[0]={name:"tom"} 

is the same as doing this:

dst[0]={newName:"tom"} 

It's considered as dst's new property instead of the one copied from src, and that is the reason the original object does not change, because this 'name' property is not the same one that was copied from the original object.

When you use the {name : "tom" } to re-assign the value to dst, then dst[0]'s memory is released from the heap and a new object replaces dst[0] altogether, it is not the same object that was shallow copied from src[0].

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. It totally makes sense now.
1

dst[0]={name:"tom"} and dst[0].name = "tom"; are not copies, they're just assignments. One changes the dst array (sets a new object as the first element), the other changes the first object (sets a new string for the .name property).

The shallow copy happens in the line let dst = [...src], and if you're not changing that it's always a shallow copy where dst contains the same mutable objects as src.

2 Comments

I agree with your statement that the spread operator is creating a shallow copy here. But my confusion is in spite of both being assignment operations post shallow copy, operation 1 does not change the contents of src while operation 2 does change the contents of src.
@ryan The second one doesn't change the src or dst array themselves. It changes the object that both arrays contain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.