Asking for help forUse Destructuring Assignment with the Rest Parameter to Reassign Array Elements

hey I didn’t understand this line so far
const[a,b,...arr]=list;
can anyone explain it to me?


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);

  **Your browser information:**

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

Challenge: Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements

Link to the challenge:

Your code worked!

If you check the previous challenge, destructuring allows us to choose which elements you want to assign to variables.

…arr allows us to collect the rest of the(or remaining) elements into a separate array. Which means it has returned everything except a and b from the source.

1 Like

Hi @zineb.akerkkaou999 !

I added spoiler tags around your code since it is a full working solution and we don’t want to spoil it for those who haven’t done this challenge yet.

1 Like

so we’ve the right to declare a constant that will hold the remaining elements !
the thing that confused me is the possibility to replace …arr with another elements i mean for example

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

and my second question how we could use the function slice in that code ?

Good question!
I believe …arr is a reserved word so it cannot be replaced with other terms inside the array inorder to assign the remaining values.
The result of …arr is very much similar to Array.prototype.slice() but …arr is just simplified way to do the same thing.

more explained in the above link. It needs some practice but you can press the run button (in the above link) to understand the logic. Hopefully, this answers your second question.

1 Like

Nope. Nothing special about the name arr. It’s just a variable name.

The line

const [a, b, ...args] = list;

Just says to break apart the array list, saving the first two elements into the variables a and b while putting ‘the rest’ of the list into the variable arr.

2 Likes

Thank you so much for spending time answering my questions , I do really appreciate that :relaxed:

Alright , thank you so much for the explanation :relaxed:

Aaah good to know. Makes sense. Thanks for answering.

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