Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need explanation for array destructuring with spread operator

How does the spread operator within the array destructuring of y3 work?

The result would contain both 'lizard' and 'spock', but because of the spread operator around the square brackets, it somehow only contains 'lizard'.

Thanks in advance for the help.

function myFunction(y1, y2, ...y3) {
  console.log(y3)
  const [x1, ...[result]] = y3;
  console.log(result);
}

const myArray = ['rock', 'paper', 'scissors', 'lizard', 'spock'];

myFunction(...myArray);
like image 934
Cjmaret Avatar asked Oct 19 '25 03:10

Cjmaret


1 Answers

In the const declaration:

const [x1, ...[result]] = y3;

the variable x1 will pluck the first element of array y3. The spread, then, will refer to the rest of y3. After the spread syntax, you have another destructuring request, this time to pluck out the first element of the array "created" by the spread (that is, the last two elements of y3). That first element is "lizard".

Without the inner square brackets, result would be the real (yes, created) array ["lizard", "spock"].

Note that spread syntax is not part of the expression grammar, and ... is not an operator.

like image 142
Pointy Avatar answered Oct 20 '25 18:10

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!