UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Generator

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Generator is a subclass of the hidden Iterator class.

Constructor

The Generator constructor is not available globally. Instances of Generator must be returned from generator functions:

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

const gen = generator(); // "Generator { }"

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

In fact, there's no JavaScript entity that corresponds to the Generator constructor. There's only a hidden object which is the prototype object shared by all objects created by generator functions. This object is often stylized as Generator.prototype to make it look like a class, but it should be more appropriately called GeneratorFunction.prototype.prototype, because GeneratorFunction is an actual JavaScript entity.

Instance properties

These properties are defined on Generator.prototype and shared by all Generator instances.

Instance methods

Also inherits instance methods from its parent Iterator.

Examples

An infinite iterator

With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.

function* infinite() {
  let index = 0;

  while (true) {
    yield index++;
  }
}

const generator = infinite(); // "Generator { }"

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …

Specifications

Browser compatibility

See also