DEV Community

Discussion on: 6 Use Cases of Spread with Array in JavaScript

Collapse
 
huncyrus profile image
huncyrus

Side note: The new Set() and the spread operator could be quite dangerous, worth to check out the behaviour: it is really copy by value or just by reference... (might be handy this small detail when ppl workin' on large datasets)

Collapse
 
samanthaming profile image
Samantha Ming

But wouldn't spread be creating a true new copy? -- do you mind expanding your thought, might be something helpful to include in my code notes ๐Ÿ˜ต

Collapse
 
penge profile image
Pavel Bucka

Try this:

const set = new Set([{ id: 1, color: "blue" }, { id: 2, color: "red" }, { id: 3, color: "green" }]);

const arr = [...set];
arr[0].color = "purple";

console.log(set); // check the first entry
// or set.values().next().value.color

The conclusion is: spreading results in a shallow copy.

Source: stackoverflow.com/questions/500511...

That means, copying primitive values turns fine. What you can do in case of objects copy, is to make a copy of those underlying objects:

const arr2 = [...set].map(item => Object.assign({}, item));
arr2[0].color = "yellow";

console.log(set); // check the first entry

But how about nested objects? Try this:

const set = new Set([{ id: 1, color: "blue", details: { weight: 10 } }, { id: 2, color: "red", details: { weight: 20 } }, { id: 3, color: "green", details: { weight: 30 } }]);

const arr2 = [...set].map(item => Object.assign({}, item));
arr2[0].details.weight = 12;

console.log(set); // check the first entry

The conclusion is: Object.assign copies property values only (not a deep copy).

Source: developer.mozilla.org/en-US/docs/W...


Conclusions:

- spreading results in a shallow copy
- Object.assign copies property values only (not a deep copy)