ES6 cheatsheet  —  Generators

Headshot Mihai Serban

Serban Mihai / 20 October 2018

~2 min read

ES6 generators

A generator is a function which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

Generators in JavaScript are a very powerful tool for asynchronous programming as they mitigate the problems with callbacks, such as Callback Hell and Inversion of Control.

This pattern is what async functions are built on top of.

For creating a generator function, we use function * syntax instead of just function.

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator’s next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.

The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().

Simple example:

function* generator(i) {  
  yield i;  
  yield i + 10;  

var gen = generator(10);  

console.log(;// expected output: 10  
console.log(; // expected output: 20

Example with yield*:

function* anotherGenerator(i) {  
  yield i + 1;  
  yield i + 2;  
  yield i + 3;  

function* generator(i) {  
  yield i;  
  yield* anotherGenerator(i);  
  yield i + 10;  

var gen = generator(10);  

console.log(; // 10  
console.log(; // 11  
console.log(; // 12  
console.log(; // 13  
console.log(; // 20

Infinite Data generator example:

function * naturalNumbers() {  
  let num = 1;  
  while (true) {  
    yield num;  
    num = num + 1  
const numbers = naturalNumbers();

console.log( // 1
console.log( // 2 

You can find a more complete ES6 cheetsheet on my Github page.

P.S. If you ❤️ this, make sure to follow me on Twitter, and share this with your friends 😀🙏🏻

gatsby  +  contentful  +  netlify  = ❤️[Source code]