Question about destructuring assignment

Use destructuring assignment with the rest parameter to perform an effective Array.prototype.slice() so that arr is a sub-array of the original array source with the first two elements omitted.

const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  // Only change code below this line
  const [a, b, ...arr] = list; // Change this line
  // Only change code above this line
  return arr;
}
const arr = removeFirstTwo(source);

console.log(arr);

My confusion is why is “list” being used here instead of just using source like so (I know it says only change code on the one line, but I am just trying to understand why it is the way it is),

const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo() {
  // Only change code below this line
  const [a, b, ...arr] = source; // Change this line
  // Only change code above this line
  return arr;
}
const arr = removeFirstTwo(source);

console.log(arr);

It’s generally not a good idea to rely upon global variables. A function shouldn’t require knowledge about external data, just the data that it requires in the form of arguments. Additionally, if you use the global variable source you can only ever remove the first two values of that single array. What if I had multiple arrays that would like the first two values removed from?

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.