DEV Community

Discussion on: Deep vs Shallow Copy - with Examples

Collapse
 
laurieontech profile image
Laurie • Edited

Oh interesting. I just played around with this a bit. And found this.

> let arr = [1,2,3]
> arr[10] = 11
11
> arr
[ 1, 2, 3, <7 empty items>, 11 ]

So it makes sense that the spread syntax would copy that same array.

According to the spec, forEach elides missing array items, so all of those undefined elements won't be accounted for. Why it doesn't in the final case I don't know. Will have to come back and look into a bit.

Thanks for the example!

Collapse
 
juliang profile image
Julian Garamendy

I just didn't know that arr.slice() and [...arr] are not equivalent.

Here's another example, without forEach.

arr.slice() vs [...arr]

const arr = [{name:'A'},{name:'B'},{name:'C'}]
arr[10] = {name:'D'}

console.log(arr.slice().map(obj => obj.name)) // ["A", "B", "C", empty × 7, "D"]
console.log([...arr].map(obj => obj.name)) // Uncaught TypeError: Cannot read property 'name' of undefined
Thread Thread
 
laurieontech profile image
Laurie

So this is what I see

let arr = [1,2,3]
> arr[5] = 1
> arr.slice()
[ 1, 2, 3, <2 empty items>, 1 ]
> [...arr]
[ 1, 2, 3, undefined, undefined, 1 ]

But no docs are telling me why that's the case. Still searching because I genuinely want to know!

Thread Thread
 
laurieontech profile image
Laurie • Edited

So the difference is holes in an array versus undefined elements. And that happens due to this:

Also explained this way:

Thread Thread
 
juliang profile image
Julian Garamendy

Awesome! Thank you!