JavaScript: Generator

By Xah Lee. Date: . Last updated: .

New in JS2015.

Generator object is a object that conforms to both the Iterator and Iterable interfaces.

[see Interface]

[see 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 Generator Function]

JavaScript Iterable 🌟

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc