A generator, when invoked, returns an iterator. We could for example loop through the iterator with a for … of
loop:
for (const item of gen()) {
console.log(item);
}
Which would just go through each item in the generator:
0
1
2
The same things happens, if we invoke the spread syntax:
const res = [...gen()];
res
would then be:
[0, 1, 2]
In your example, you're using a destructuring assignment. Destructuring with the bracket syntax invokes the iterable to get the values (same principle for arrays). Example:
const [a, b] = gen();
// a: 0, b: 1
Since you're using the rest syntax, you're basically saying: Give me all the values that are left in the iterator, and save them in the variable b
:
let [...b] = gen();
// b: [0, 1, 2]
This works on any iterable:
const [a, b, ...c] = 'hello';
// a: 'h', b: 'e', c: 'llo'
Personally, I find the following a lot easier to reason about:
const res = [...gen()];