JS: Generator

By Xah Lee. Date: . Last updated: .

New in ES2015.

Generator object is a object that 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]

Create Generator

To create a generator, you can either write it manually, this is hard and tedious.

Generator Function is designed to create generators.

[see JS: Generator Function]

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 $5 at patreon.

Or, Buy JavaScript in Depth

JS Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog