Javascript ES6 Generator Functions

January 12, 2019

What does the “yield” keyword do?

What is the use of the yield keyword? What does it do?

Yield and Generator functions

Generator functions are great in the sense that they allow for exiting and re-entering while maintaining the state. Inspired by Python, here to stay for the best! Functions that can be exited and re-entered.

Example 1:

function* idMaker() {
  var index = 0;
  while (true)
    yield index++;

var gen = idMaker();

console.log(; // {value: 0, done: false}
console.log(; // {value: 1, done: false}

As you can see in the example above, the state of the function is maintained, because the index variable is accumulated every time we go back to the function.

Now there is a field named done that gets returned from each .next() call. The value specifies whether or not this is the last value the generator is yielding

Example 2:

function* idMaker(stopAt) {
  var index = 0;
  while (index < stopAt)
    yield index++;

  return stopAt;

var gen = idMaker(2);

console.log(; // {value: 0, done: false}
console.log(; // {value: 1, done: false}
console.log(; // {value: 2, done: true}

You can also grab arguments without using a reference in the generator.

Example 3:

function* logGenerator() {
  console.log(1, yield);
  console.log(2, yield);
  console.log(3, yield);

var gen = logGenerator();;             // 0'pretzel');    // 1 pretzel'california'); // 2 california'mayonnaise'); // 3 mayonnaise
                        // {value: undefined, done: false}