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);
CodePudding user response:
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.