DEV Community

Discussion on: Deep vs Shallow Copy - with Examples

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!