In the video, Ngozi swapped next week’s Tuesday and Thursday dinners. Each dinner sits in a meals array, inside a day record, inside the week, so the update copied every level on the way to each dinner and left the other five days shared with last week.
Key Points
- A dinner is three arrows deep.
lastWeekpoints at the week’s array, slot1points at Tuesday’s record, and itsmealsproperty points at Tuesday’s meals array. Those three objects are the path to the change, and last week reaches all of them. Change any of them in place, and last week changes too. - Copying only the day record with spread doesn’t protect the dinner. After
const nextTuesday = { ...lastWeek[1] };, the copy’smealsstill points at last week’s array, sonextTuesday.meals[1] = "bean tacos";gives last Tuesday bean tacos too. swapDinners()copies every level on the path..with(1, ...)builds a new meals array with the other day’s dinner at position1, where the dinner sits. The spread builds a new record around it, and a second.with()builds a new week with both new records in their slots. Nothing in it writes into an object it was given.- The days off the path stay shared.
nextWeek[0] === lastWeek[0]istrue, because the new week has new records only in slots1and3. Earlier,.map()copied all seven days; here you copy only the path and share the rest, so the unchanged days stay the same objects. Sharing is safe only while no code writes into the shared records or their meals, so any later change to next week has to copy its path too. - The sharing helps when you compare. As long as every update copies its path, a day that’s still shared hasn’t changed, so
===shows you which days were replaced: only Tuesday and Thursday are new. It compares arrows, not meals: afalsedoesn’t tell you whether the contents differ. - The rule: to change something nested, copy every level on the path to it, and share the rest.
Final Code
plan.js swaps two dinners in a copy of the week and leaves last week as it was: