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

Try it


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(; // 1
console.log(; // 2
console.log(; // 3

Instance properties

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


The constructor function that created the instance object. For Generator instances, the initial value is GeneratorFunction.prototype.

Note: Generator objects do not store a reference to the generator function that created them.


The initial value of the @@toStringTag property is the string "Generator". This property is used in Object.prototype.toString().

Instance methods

Returns a value yielded by the yield expression.


Acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.


Acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.


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(; // 0
console.log(; // 1
console.log(; // 2
// …


ECMAScript Language Specification
# sec-generator-objects

Browser compatibility

BCD tables only load in the browser

See also