In this lesson, you moved a tweak to the Okafors’ meal plan into a function and found out when a function changes its caller’s data.
Key Points
- The code that calls a function is its caller. When you pass an array to a function, the parameter gets the caller’s value, which is an arrow. So the parameter becomes one more arrow to the caller’s array.
removeDay(plan, position)splices the plan it’s given. It has noreturnstatement, so a call to it gives backundefined, yetremoveDay(nextWeek, 4)leavesnextWeekwith six days, because.splice()follows the arrow inplanto the arraynextWeekpoints at.- When the function ends, the parameter and its arrow disappear. The change to the array stays.
- Watch out if you try to empty the caller’s array from a function like
clearWeek(plan)by reassigning its parameter, as inplan = [];. That only swings the parameter’s own arrow to a new array, which is thrown away when the function ends. The caller’s array keeps its days. To give the caller a new array, return it, and let the caller store it. removeDay()keeps last week safe only if every caller remembers to copy first. Forget the copy once, andremoveDay(lastWeek, 4)splices Friday out of last week.withoutDay(plan, position)does the copying itself: it copies the plan with[...plan], splices the copy and returns it.const nextWeek = withoutDay(lastWeek, 4);gives next week six days and leaves last week with seven.- Use a function that changes its array, like
removeDay(), on an array the caller means to change. Use one that returns a new array, likewithoutDay(), when the caller needs its original. - The rule: a function changes its caller’s data only on purpose, with a name that says so. Otherwise, copy every level it changes, and return the copy.
withoutDay()only takes a slot out of the outer array, so a one-level copy is enough there.
Final Code
The final plan.js has both helpers and makes next week with the one that leaves last week alone: