Lesson 50 +20 XP

Generators

Generators

A generator is a function that can pause and resume. It produces a sequence of values on demand.

Creating a generator

Use function* and the yield keyword:

function* countUp() {
  yield 1;
  yield 2;
  yield 3;
}

Using a generator

const gen = countUp();
gen.next(); // { value: 1, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 3, done: false }
gen.next(); // { value: undefined, done: true }

The star syntax

function* (function with a star) declares a generator. You call it to get an iterator, not to run the body.

Yield pauses

Each yield pauses the function and hands out a value. The function continues when you call next() again.

Generators are iterable

You can loop a generator with for...of:

for (let n of countUp()) {
  console.log(n); // 1, 2, 3
}

Infinite generators

Generators can produce endless sequences because they only compute on demand:

function* forever() {
  let i = 0;
  while (true) {
    yield i++;
  }
}

TL;DR

  • Generators are functions with function*.
  • yield hands out a value and pauses.
  • next() resumes the generator.
  • Generators are iterable and can be infinite.