Creating an array from ES6 generator

Viewed 2208

Let's say I want to assign the result of an ES6 generator to an array variable.

function* gen() {
   for(let i = 0; i < 3; i++) {
       yield i;
   }
}

let [...b] = gen();
console.log(b); // [0, 1, 2]

Here b will be assigned [0, 1, 2]. Why does this work?

3 Answers

For actually creating an array from a generator function there are some answers here which are pretty good. I personally prefer Array.from:

function* gen() {
   for(let i = 0; i < 3; i++) {
       yield i;
   }
}

const arr = Array.from(gen());
console.log(arr); // [0, 1, 2]
Related