/* 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.*/
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter