In the last video, you spread the recipe box’s prep times into Math.max(), and the rest parameter ...meals gathered a day’s extra meals into a new array. Spread inside square brackets builds new arrays too, but some of the tools from the first lesson don’t.
Back then, .reverse() and .splice() changed the array you called them on, which was fine for a scratch list of dinners. For next week’s plan, a change in place is how last week gets rewritten by accident.
In this lesson, you’ll use the array methods that return an edited copy instead. You’ll be able to reverse arrays and remove, insert, and replace items. You’ll also change one day of the week while lastWeek stays exactly as it was. Start with a pair of methods you already know.
Pair Each Method With Its Copying Twin
Some array methods change their array, and others hand you a new one. You’ve already met both kinds. The .sort() method rearranges its array in place, while .toSorted() returns a sorted copy, and .map() and .filter() always build new arrays. The recipe box’s prep times show the difference in a few lines:
recap.js
const prepMinutes = [60, 25, 40];
const quickest = prepMinutes.toSorted((a, b) => a - b);
console.log("Quickest:", quickest);
console.log("Original:", prepMinutes);
Run it, and only the copy is sorted:
$ node recap.js
Quickest: [ 25, 40, 60 ]
Original: [ 60, 25, 40 ]
The same naming pattern covers the two methods from the first lesson. The .toReversed() method is the copying version of .reverse(), and .toSpliced() is the copying version of .splice(). Each to method takes the same arguments as its in-place twin and returns a new array with the change applied.
In the first lesson, meals.reverse() swapped Monday’s lunch and dinner by rewriting Monday’s meals array. Create monday.js and do the same swap with .toReversed():