re: 5 Uses for the Spread Operator VIEW POST


Copying an array

Why would you copy an array like this, rather than let copy = arr ?


Because of it being a shallow copy.

let copy = [1, 2, 3]
let arr = copy
// 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 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.


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

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

Code of Conduct Report abuse