JavaScript: Generator

By Xah Lee. Date: . Last updated: .

New in ES2015.

A Generator object is a instance of (returned by) a call of generator function.

〔►see JavaScript: Generator Function

Generator object conforms to both the Iterator and Iterable interfaces.

〔►see JavaScript: Interface

This means, generator are iterable, and you can use for-of Loop on it.

〔►see JavaScript: Iterable

〔►see JavaScript: for-of Loop

Generator as Iterable

Example of using generator as iterable.

// example of using generator as iterable

// define a generator function
function * ff () {
    yield 3;
    yield 4;
    yield 5;
}

// generator function returns a generator object
const gg = ff();
// now gg is a generator object

// because generator is also a iterable object

// we can use for-of loop on iterable object
for (let p of gg) {
    console.log ( p );
}
// prints
// 3
// 4
// 5

〔►see JavaScript: Generator Function

Generator as Iterator

Example of using generator as an iterator.

// Example of using generator as an iterator

// define a generator function
function * ff () {
    yield 3;
    yield 4;
    yield 5;
}

// generator function returns a generator object
const gg = ff();
// now gg is a generator

// because generator is also a iterator, so it has next() method

// call generator object by using the “next()” method
console.log(gg.next()); // { value: 3, done: false }

console.log(gg.next()); // { value: 4, done: false }

console.log(gg.next()); // { value: 5, done: false }

console.log(gg.next()); //{ value: undefined, done: true }

console.log(gg.next()); //{ value: undefined, done: true }

Reference

ECMAScript 2015 §Control Abstraction Objects#sec-generator-objects

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.

Iterable / Iterator / Generator Topic

  1. JavaScript: Interface
  2. JavaScript: Iterable
  3. JavaScript: Iterator
  4. JavaScript: for-of Loop
  5. JavaScript: Generator Function
  6. JavaScript: Generator