Search code examples
javascriptecmascript-6generator

Creating an array from ES6 generator


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?


Solution

  • Well I think I found the answer on this post. The ... operator here is the rest operator. When used to destructure an array, it will assign all unassigned elements of the array being destructured to another array. The rest operator must be used on the last item in the list of variables receiving the destructured values. For example:

    let a = [1, 2, 3, 4, 5];
    let [first, second, ...remainder] = a;
    
    console.log(first); // 1
    console.log(second); // 2
    console.log(remainder); // [3, 4, 5]

    In the question, since b is the only thing being destructured and its using the rest operator, the entire array is assigned to it.

    ES6 appears to run the generator and turn the result into an array on the right hand side of the =.