In the video, lastWeek and nextWeek looked like two meal plans, but they were two names for one array, so dropping Friday from one dropped it from both.
Key Points
- A name points at an array, like an arrow.
const nextWeek = lastWeek;doesn’t build anything: it gives the same array a second arrow. - Change that one array through either name, as
nextWeek.splice(4, 1)does, and both names see it. Changing an array in place is called mutation. .reverse()hands back the same array too: afterconst flipped = meals.reverse();,flippedandmealsboth show the flip.constfixes only the arrow. It stops reassignment (lastWeek = []throwsTypeError: Assignment to constant variable.), but it doesn’t stop mutation of the array.- To give a name its own array, make a new one.
lastWeek.slice()with no arguments copies the whole array into a new one. - The rule: an equals sign copies the arrow, not the array.
Final Code
Here is plan.js as the lesson leaves it. With .slice(), nextWeek gets its own array, so dropping Friday leaves lastWeek alone:
const lastWeek = [
{ day: "Monday", cook: "Ngozi", meals: ["leftover rice", "jollof rice"] },
{ day: "Tuesday", cook: "Chidi", meals: ["egg sandwiches", "pepper soup"] },
{ day: "Wednesday", cook: "Ada", meals: ["pepper soup", "spaghetti and meatballs"] },
{ day: "Thursday", cook: "Emeka", meals: ["salad wraps", "bean tacos"] },
{ day: "Friday", cook: "Chidi", meals: ["bean tacos", "takeout pizza"] },
{ day: "Saturday", cook: "Ada", meals: ["pancakes", "veggie stir-fry"] },
{ day: "Sunday", cook: "Grandma Ifeoma", meals: ["moi moi", "chicken curry"] },
];
const nextWeek = lastWeek.slice();
nextWeek.splice(4, 1);
console.log("Next week:", nextWeek.length, "days");
console.log("Last week:", lastWeek.length, "days");
Running node plan.js prints:
Next week: 6 days
Last week: 7 days
Each slot of that copy still holds a day record. In the next lesson, Make Shallow Copies, you’ll find out what the copy shares with lastWeek.