In the below code,
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
Is spread operator(...
) unpacki
Yes, that's exactly what the spread operator does.
It is the equivalent of replacing the identifier containing the iterable with an comma seperated list of values that are the output of iterating the iterable.
In your case, the iterable is an array, and the equivalent is 0, 1, 2
.
Had the iterable been the output of a generator function it would be the same:
function* f1() {
yield 1;
yield 2;
yield 3;
}
var a = [...f1()];
// the above is IDENTICAL to [1, 2, 3]
A powerful use of the operator is when values are not "static" like this:
function* f2(totalCount) {
let count= 1;
while(totalCount-- > 0) {
yield count++;
}
}
var b = [...f2(5)];
// b is equal to [1, 2, 3, 4, 5]