const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
openingHours: {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0, // Open 24 hours
close: 24,
},
},
orderPasta: function (ing1, ing2, ing3) {
console.log(`Pasta made with ${ing1}, ${ing2} and ${ing3}`);
},
};
const arr = [7, 8, 9];
const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
console.log(badNewArr);
const newArr = [1, 2, ...arr];
console.log(newArr);
console.log(...newArr);
const newMenu = [...restaurant.mainMenu, 'Gnocci'];
console.log(newMenu);
const mainMenuCopy = [...restaurant.mainMenu]; // similar to Object.assign()
const bigMenu = [...restaurant.starterMenu, ...restaurant.mainMenu];
Spread operator works on all iterables (array, string, map, set. NOT object)
const str = 'Jonas';
const letters = [...str, ' ', 'S.'];
console.log(letters);
// this won't work as spread operator can only be put into place that expect values seperated by comma
// console.log(`${...str} Schedtmann`);
const ingredients = [
prompt("Let's make pasta! Ingredient 1?"),
prompt('Ingredient 2?'),
prompt('Ingredient 3?'),
];
console.log(ingredients);
restaurant.orderPasta(...ingredients);
Since ES 2018, spread operator also work with object
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe' };
console.log(newRestaurant);
const restaurantCopy = { ...restaurant };
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurantCopy.name); // new name
console.log(restaurant.name); // old object's name doesn't change, we have successfully made a shallow copy of the old object