In the video, the same three dots worked in two directions. They spread the recipe box’s prep times out into a call to Math.max(), and they gathered Grandma Ifeoma’s extra dishes, and what was left of the recipe box, up into new arrays and objects.
Key Points
Math.max()takes its numbers as separate arguments.Math.max(...prepMinutes)takes each item out of the array, in order, and passes it as its own argument, so it’s the same call asMath.max(60, 45, 25, 50, 35)and returns60.- Spread doesn’t change the array it spreads:
prepMinuteskeeps its five prep times, in order. - Without the dots,
Math.max(prepMinutes)gets one argument, the whole array.Math.max()tries to turn that argument into a number, and five numbers can’t become one, so it returnsNaN. - Spreading a string into a new array gives one letter per item:
[..."egusi"]is[ 'e', 'g', 'u', 's', 'i' ]. - In a parameter list, the dots gather. In
function addMeals(record, ...meals), every argument after the day record lands in one new array,meals. That’s a rest parameter. With two dishes,mealsholds two, with one it holds one, and with none it’s an empty array,[]. In the body,[...record.meals, ...meals]builds a new array, where values go, so the same...mealsspreads the gathered dishes back out after the record’s own meals. - Patterns gather too.
const [first, ...others] = recipes;puts the first recipe infirstand the other four in a new array,others, whilerecipeskeeps all five.const { day, ...rest } = monday;puts every property the pattern didn’t name, the cook and the meals, into a new object,rest. The object is new, but its meals are Monday’s own array, shared, not copied. - The rest always comes last, because it takes everything that’s left.
const [...start, last] = recipes;won’t run: Node reportsSyntaxError: Rest element must be last element. A rest parameter follows the same rule. - The rule: read the three dots by where they stand, not by the brackets around them. Where values go, in a call or in a new array or object you’re building, they spread out. Where names are made, in a parameter list or a pattern on the left of the
=, they gather values up into a new array or object.
Final Code
prep.js spreads the prep times into Math.max():