In the last lesson, you unpacked Monday’s record by name and its meals by position, one line at a time. The planner script needs those values in more places than a single line at the top. A helper that prints a day receives the record as an argument, a loop visits seven records in turn, and a function that works something out often has two results to hand back.
In this lesson, you’ll put the same patterns in all three places. You’ll write a function that unpacks the record it’s given, read and write a nested pattern that reaches into a day’s meals, and unpack two results at the call site. Start with the helper that prints one day of the plan.
Unpack a Record in the Parameter List
A helper that receives a day record has to dig into it on every line. Written the long way, a printDay(record) function repeats record.day, record.cook, and record.meals wherever it needs a value, and the name record says nothing about what’s inside.
A parameter can be a pattern instead of a name. Create printday.js with a helper whose parameter is the pattern you wrote in the last lesson:
printday.js
const monday = {
day: "Monday",
cook: "Ngozi",
meals: ["leftover rice", "jollof rice"],
};
function printDay({ day, cook, meals }) {
console.log(day, "is cooked by", cook);
console.log(" Dinner:", meals[1]);
}
printDay(monday);
Run it, and the helper prints Monday from three variables it never declared in its body:
$ node printday.js
Monday is cooked by Ngozi
Dinner: jollof rice
When you call printDay(monday), JavaScript takes the argument and unpacks it as if the function’s first line were let { day, cook, meals } = monday;, so day, cook, and meals are local names inside the function. The pattern also documents the function, since anyone reading its first line can see that it expects a record with day, cook, and meals.
Unpacking doesn’t copy what it takes out, though. The local name meals that the pattern creates holds the same reference as monday.meals, so both names reach one array. A meals.push() inside the helper changes the array that monday.meals points to.