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


This object cannot be instantiated directly. Instead, a Generator instance can be returned from a generator function:

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

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

console.log(; // 1
console.log(; // 2
console.log(; // 3

Instance methods

Returns a value yielded by the yield expression.


Returns the given value and finishes the generator.


Throws an error to a generator (also finishes the generator, unless caught from within that generator).


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