I passed but, i still don't understand what this : Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements is

Tell us what’s happening:

How is: Array.prototype.slice() related to the lesson?

Your code so far


const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
"use strict";
// Only change code below this line
const arr = [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/83.0.4103.116 Safari/537.36.

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

Link to the challenge:

Hello there,

Array.prototype.slice returns a portion of the array back. Example:

const source = [1,2,3,4,5,6,7,8,9,10];
const arr = source.slice(2);
console.log(arr)

Essentially, before destructuring, this is what you would have to do.

I hope that shows the similarity.

1 Like

Is it because it only takes the 1st 3 value’s of the array?
That it is simulair to slicing

In this line

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

The part inside the brackets ([]) already takes care of the assignment, so you cannot have a const arr = ... at the beginning. This would be akin to writing

const variable1 = const variable2 = variable3;

Which is syntactically wrong.

Instead, it should be written as

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

a and b get assigned to the first and second values of the list array respectively, while the array variable gets assigned to the rest of the list.

As to how this relates to the slice method, the above is in essence equal to the following:

const a = list.slice(0,1); // a = 1
const b = list.slice(1,2); // b = 2
const arr = list.slice(2); // arr = [3, 4, 5, 6, 7, 8, 9, 10]

As you can see, destructuring with the rest parameter is much more efficient, since you can get it all done in one line, and don’t have to bother with determining the correct start and end indices, which you must do with the slice method.

As a final note, since you do not care at all about the first and second values in the list, the assignment to the a and b variables is essentially useless. And there is a way to avoid this situation:

const [, , ...arr] = list; // arr = [3, 4, 5, 6, 7, 8, 9, 10]

By placing two commas, yet not supplying a variable name, we are essentially skipping over the first two items, and assigning the rest to the arr variable.

With warm regards,
Onur Bal

1 Like