spread operator (copying objects)
Fri Mar 08 2024 09:42:45 GMT+0000 (Coordinated Universal Time)
Saved by
@manami_13
/* In this case, we're creating a new object and spreading properties of the restaurant object, so we're not copying a reference to the same object, but we actually create a new object */
const restaurantCopy = { ...restaurant };
/*Note that the name property of the restaurant object is a string (primitive), and not a reference type. That's why it was copied "by value", and not "by reference".
However, if the name property would store an object, it would copy a reference to that object, instead of copying the object itself. Here's an example:*/
const restaurant = {name: {value: 'Classico Italiano'}};
const restaurantCopy = { ...restaurant };
restaurantCopy.name.value = 'Ristorante Roma';
console.log(restaurantCopy.name.value); // Ristorante Roma
console.log(restaurant.name.value); // Ristorante Roma
/*Now, the name property stores an object. Copying this property copies a reference to that object, and not the object itself. That's why modifying it through the copied restaurant object also changes it in the original restaurant object.*/
content_copyCOPY
Comments