JS: 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 JS: Generator Function]

Generator object conforms to both the Iterator and Iterable interfaces.

[see JS: Interface]

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

[see JS: Iterable]

[see JS: 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 JS: 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

Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth

Iterable / Iterator / Generator Topic

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