DEV Community

loading...

Discussion on: 3 Ways to Clone Objects in JavaScript

Collapse
adameier profile image
adam meier • Edited

I'ts important to note that Object.assign is a function which modifies and returns the target object. In Samantha's example using the following,

const cloneFood = Object.assign({}, food)
Enter fullscreen mode Exit fullscreen mode

{} is the object that is modified. The target object is not referenced by any variable at that point, but because Object.assign returns the target object, we are able to store the resulting assigned object into the cloneFood variable. We could switch our example up and use the following:

const food = { beef: '🌽', bacon: '🥓' };

Object.assign(food, { beef: '🥩' });

console.log(food);
// { beef: '🥩', bacon: '🥓' }
Enter fullscreen mode Exit fullscreen mode

Obviously the value of beef in our food object is wrong, so we can assign the correct value of beef using Object.assign. We aren't actually using the returned value of the function at all, but we are modifying our target object which we have referenced with the const food.

Spread on the other hand is an operator which copies properties of one object into a new object. If we wanted to replicate the above example using spread to modify our variable food...

const food = { beef: '🌽', bacon: '🥓' };

food = {
  ...food,
  beef: '🥩',
}
// TypeError: invalid assignment to const `food'
Enter fullscreen mode Exit fullscreen mode

...we get an error, because we use spread when creating new objects, and therefore are assigning a whole new object to food which was declared with const, which is illegal. So we can either choose to declare a new variable to hold our new object in, like the following:

const food = { beef: '🌽', bacon: '🥓' };

const newFood = {
  ...food,
  beef: '🥩',
}

console.log(newFood);
// { beef: '🥩', bacon: '🥓' }
Enter fullscreen mode Exit fullscreen mode

or we could declare food with let or var which would allow us to assign a whole new object:

let food = { beef: '🌽', bacon: '🥓' };

food = {
  ...food,
  beef: '🥩',
}

console.log(food);
// { beef: '🥩', bacon: '🥓' }
Enter fullscreen mode Exit fullscreen mode
Collapse
patrickjsmirnov profile image
Dmitriy Smirnov

Got it. Thank you!

Collapse
samanthaming profile image
Samantha Ming Author

Thanks for chiming in and helping answer this question. This is great, let me add it to the code notes 🙂