DEV Community

Discussion on: 5 Uses for the Spread Operator

Collapse
 
laurieontech profile image
Laurie • Edited

Because of it being a shallow copy.

let copy = [1, 2, 3]
let arr = copy
copy.push(4)
// copy is [1,2,3,4]
// arr is [1,2,3,4]

The spread operator would mean this

let copy = [1, 2, 3]
let arr = [...copy]
copy.push(4)
// copy is [1,2,3,4]
// arr is [1,2,3]

However, this only works for flattened arrays. Multidimensional arrays will be deep copies at only the top level.

Collapse
 
nataliedeweerd profile image
𝐍𝐚𝐭𝐚𝐥𝐢𝐞 𝐝𝐞 𝐖𝐞𝐞𝐫𝐝

Thank you for explaining! :)

Collapse
 
seanmclem profile image
Seanmclem

It does a deep copy for an array only, but does a shallow copy when used on an object. Is that right? Doesn't mention it in your article

Thread Thread
 
laurieontech profile image
Laurie

That is correct. And yes, it's something that I likely should have mentioned!