docs.rodeo

MDN Web Docs mirror

Generator

{{JSRef}} 

The Generator object is returned by a {{jsxref("Statements/function*", "generator function", "", 1)}}  and it conforms to both the iterable protocol and the iterator protocol.

Generator is a subclass of the hidden {{jsxref("Iterator")}}  class.

{{InteractiveExample("JavaScript Demo: Expressions - function* expression", "taller")}} 

const foo = function* () {
  yield "a";
  yield "b";
  yield "c";
};

let str = "";
for (const val of foo()) {
  str = str + val;
}

console.log(str);
// Expected output: "abc"

Constructor

There’s no JavaScript entity that corresponds to the Generator constructor. 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

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 {{jsxref("GeneratorFunction.prototype.prototype")}} , because GeneratorFunction is an actual JavaScript entity. To understand the prototype chain of Generator instances, see {{jsxref("GeneratorFunction.prototype.prototype")}} .

Instance properties

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

Instance methods

Also inherits instance methods from its parent {{jsxref("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

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN