In the exercise, you compared day records by their meals and unpacked them into variables. Earlier, in Make Shallow Copies, you met three dots twice: [...lastWeek] copied the week, and { ...day } copied a day record. Those dots are spread syntax, and copying is only its most basic use.
In this lesson, you’ll use spread to build new arrays and records from old ones. You’ll join lists, add items, and change one property of a day while the original stays as it was. You’ll also be able to predict the result of a merge when two objects share a property name. Start with the family’s shopping, where egusi soup needs a few things the Okafors don’t usually buy.
Join Arrays With Spread
The egusi soup ingredients have to join the regular grocery list. In the first lesson, you did that with .concat(), which returned a new, flat array. Spread gives you the same result, written the way the result looks. Create groceries.js:
groceries.js
const groceries = ["rice", "tomatoes", "onions"];
const egusiItems = ["egusi seeds", "spinach", "palm oil"];
const shoppingList = [...groceries, ...egusiItems, "crayfish"];
console.log("Shopping list:", shoppingList);
console.log("Groceries:", groceries);
Run it, and you get one flat list of seven items, while groceries still has three:
$ node groceries.js
Shopping list: [
'rice',
'tomatoes',
'onions',
'egusi seeds',
'spinach',
'palm oil',
'crayfish'
]
Groceries: [ 'rice', 'tomatoes', 'onions' ]
Inside square brackets, each ... unpacks one array’s items, in order, at the spot where it stands. So ...groceries puts in rice, tomatoes, and onions. Then ...egusiItems puts in the three egusi items after them, and "crayfish" is a plain item at the end. You can mix spread arrays and single items in any order. Writing ["crayfish", ...groceries] would put crayfish first.
The dots are what keep the list flat. Without them, [groceries, egusiItems] is an array that holds two arrays, the same nesting that groceries.push(egusiItems) caused in the first lesson. Spread never changes the arrays it unpacks. The square brackets build a new array, and spread only fills in its items, which is why groceries still has its original three items.
The planner joins weeks the same way, only now the items are day records. Say a short plan holds Monday and Tuesday, and an extras array holds a Wednesday the family wants to add. Create plan.js:
plan.js
const lastWeek = [
{ day: "Monday", cook: "Ngozi", meals: ["leftover rice", "jollof rice"] },
{ day: "Tuesday", cook: "Chidi", meals: ["egg sandwiches", "pepper soup"] },
];
const extras = [
{ day: "Wednesday", cook: "Ada", meals: ["pepper soup", "bean tacos"] },
];
const plan = [...lastWeek, ...extras];
console.log(plan.length, plan === lastWeek);