Using Generators in JavaScript

Posted on 05-11-2018 by Nadir Latif


Source: http://qnimate.com/javascript-yield-keyword-and-function-syntax/

Generators were introduced in ES6. One of the benefits of Generators is that they allow efficient handling of large arrays. JavaScript implements generators using the yield keyword and function* function declaration.

The function* denotes a generator function. Within the function, the yield keyword can be used. The following code describes how to use generators in JavaScript:


function* collection_name()
{
    yield 1;
    yield 3;
    yield 5;
    yield 7;
}

for(let count of collection_name())
{
    console.log(count);
}