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