Question on Destructuring - from ES6 use destructuring Assignment to Assign Variables from Arrays

Tell us what’s happening:
hey guys,

just wondering - why do we put a parameter for const arr when assigning the value of the function removeFirstTwo? it doesn’t seem like it needs it. you can remove “source” from const arr = removeFirstTwo() and it works just fine.

Your code so far


const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  "use strict";
  // change code below this line
  const [a, b, ...arr] = source; // change this
  // change code above this line
  return arr;
}
const arr = removeFirstTwo(source); //why is source here?
console.log(arr); // should be [3,4,5,6,7,8,9,10]
console.log(source); // should be [1,2,3,4,5,6,7,8,9,10];

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements

Hi,

Actually I think they were expecting you to destructure list, not source - passing the array as a parameter vs using the global variable. That way the function would work for any array, not just one named source that was in scope of the function.

console.log(removeFirstTwo([10,20,30]); // this would fail to provide a sensible result

One of the tests in the background ideally would have tested for that.

Either way you clearly understood the destructuring concept of the lesson and you were curious enough to see that something looked odd about that challenge even after you got your green checkmark so high five on that.

1 Like

Yup, got it. I think that piece is what I was missing. Now destructuring list, the function will work for whatever parameter is input. Thanks!!