16. Generators

Generator functions are a new feature in ES6 that allow a function to generate many values over time by returning an object which can be iterated over to pull values from the function one value at a time.

A generator function returns an iterable object when it’s called.
It is written using the new * syntax as well as the new yield keyword introduced in ES6.

  1. function *infiniteNumbers() {
  2. let n = 1;
  3. while (true) {
  4. yield n++;
  5. }
  6. }
  7. const numbers = infiniteNumbers(); // returns an iterable object
  8. numbers.next(); // { value: 1, done: false }
  9. numbers.next(); // { value: 2, done: false }
  10. numbers.next(); // { value: 3, done: false }

Each time yield is called, the yielded value becomes the next value in the sequence.

Also, note that generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute, or even infinite sequences.