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]

[see JS: Iterable]

Create Generator

To create a generator:

Write Generator by Hand

// create a iterator
const xiterator = {};
xiterator.i = 0;
xiterator.next = (() => ( (xiterator.i < 3) ? { value: xiterator.i++, done: false } : { value: undefined, done: true } ));

// create a generator
const xgenerator = {};

// add a Symbol.iterator property, so it conforms iterable interface
xgenerator[Symbol.iterator] = (() => xiterator);

// add a next property, so it conforms iterator interface
xgenerator.next = xiterator.next;

// test it as a iterable
console.log (
[...xgenerator]
 );
// [ 0, 1, 2 ]

// test it as a iterator
// call generator object by using the “next()” method
console.log(xgenerator.next());
console.log(xgenerator.next());
console.log(xgenerator.next());
// prints
// { value: undefined, done: true }
// { value: undefined, done: true }
// { value: undefined, done: true }
// because already reached end when we tested it using spread operator

Create Generator by Generator Function

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

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


// test it as iterable by using spread operator
console.log ( xgenerator.next() );
console.log ( xgenerator.next() );
console.log ( xgenerator.next() );
// { value: 3, done: false }
// { value: 4, done: false }
// { value: 5, done: false }

// test generator as iterable by using spread operator
console.log ( [...xgenerator] );
// []
// empty because already reached the end when we test it using next

[see JS: Generator Function]

Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, 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 Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog