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(gen.next()); // {value: 0, done: false}
console.log(gen.next()); // {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(gen.next()); // {value: 0, done: false}
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 2, done: true}

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

Example 3:

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

var gen = logGenerator();

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