DEV Community

Star
Star

Posted on

Destructing Assignment w/ Rest Parameter to Reassign Array Elements

Destructing Assignment w/ Rest Parameter to Reassign Array Elements

MDN Destructing Reference
So this was yet another dumb thing that seemed easy at first, but I’m not sure how I keep getting lost.
I thought that I had to create a new variable to break the source array into arr and list. But what I actually had to do was using the Destructing Assignment Parameter[a, b, …arr] which would automatically take the values in slot A and slot B and drop them off the face of the earth, resulting in just the remaining or THE REST of the array thereafter.

The function removeFirstTwo(list) says there is a const[a, b, …arr] = list; which will seperate slots a, and b just as intended, but I’m not clear on how those two and …arr are not included within list. Why does removeFirstTwo(list) not also show slots a and b?
I think this is due to the return only including arr, which again, confuses me, because why does the function use the parameter of list instead of arr if it is returning arr.
The function uses the parameter of list instead of the returned arr, because list refers to what was gathered within arr. We’re not creating a new array, we’re just modifying the array that was given to the function removeFirstTwo.

I think the MDN example on Destructing seems to explain this a bit clearer

MDN Example - Array Destructing - Basic Variable Assignment

const foo = ['one', 'two', 'three'];

const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"

Enter fullscreen mode Exit fullscreen mode

My submitted code

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)