liveBook · Manning

Generator

As explained in Functional Programming in JavaScript

A JavaScript function form that can pause and resume execution, yielding a sequence of values over time.

A generator is a JavaScript function form that can pause with yield and resume later, keeping its local variables between pauses. It produces values on demand instead of building an entire collection first, making it useful for large or potentially infinite data sequences. section 8.3

Generate values on demand

function* range(start = 0, finish = Number.POSITIVE_INFINITY) { for (let i = start; i < finish; i++) { yield i; } }\n\nconst numbers = range(1);\nnumbers.next().value; // 1\nnumbers.next().value; // 2\n\nA for...of loop can consume values until a chosen stopping point, so an infinite range does not need to finish producing. section 8.3

function *range(start = 0, finish = Number.POSITIVE_INFINITY) {
  for(let i = start; i < finish; i++) {
     yield i;                                      #1
  }
}
const num = range(1);
num.next().value; //-> 1
num.next().value; //-> 2
num.next().value; //-> 3
// or
for (let n of range(1)) {                          #2
  console.log(n); 
  if(n === threshold) {                            #3
     break;
  }
}// -> 1,2,3,...

Inspect the range generator, its next() calls, and its for...of usage. section 8.3

Generators can also transform values, compose nested generators with yield*, and traverse structures such as trees. Their lazy iterators offer another approach to asynchronous code alongside promises and functional reactive programming. section 8.3 section 8.5

How Functional Programming in JavaScript covers it

How deep it goes
Explains function* syntax, yield, saved execution context, iterators, composition, and traversal, without detailing iterator internals.
Examples
Uses range generation, bounded consumption, squared values, nested student generators, and recursive tree traversal.
What it assumes
Assumes JavaScript functions and explains execution context, eager evaluation, and iterator-based production around the feature.
What you can do after
Apply it via JavaScript generators to create, transform, consume, and compose lazy sequences.
How it connects
Connects generators with iterators, lazy evaluation, promises, asynchronous code, and functional reactive programming.

Also explained in

Compare how 12 books explain generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.