liveBook · Manning

Generator

As explained in Secrets of the JavaScript Ninja, Third Edition

A generator is a JavaScript function whose execution can suspend and resume while producing a sequence of values through an iterator.

A generator function produces an iterable whose execution can pause and resume. Declare one with function*; calling it returns a generator object, which is both an iterator and an iterable. section 8.3.2

Each call to next() runs the function until it reaches yield or returns. yield pauses that function—not the JavaScript thread—and the next call resumes it. Results have value and done properties; next(value) can also pass a value back into the suspended generator. section 8.3.2

Generators support several patterns:

  • Use a generator as an iterable, such as an infinite sequence of random numbers. section 8.3.2
  • Use yield* to delegate iteration to another generator. section 8.3.2
  • Combine generators with async and await to produce async iterators for for await...of loops. section 8.4
Listing 8.11 Defining an infinitely iterable generator
function* randomNumbers() { #A
  while (true) { #B
    yield Math.random(); #B
  } #B
}

const randomNumberGenerator = randomNumbers(); #C
const [num1, num2] = randomNumberGenerator; #D
console.log(num1, num2);

This infinite random-number generator shows how yield produces values on demand. section 8.3.2

Generators were expected to help replace nested callbacks, but few developers adopted their syntax; async/await later displaced one major use case. They remain useful in some scenarios, though they are now regarded as a niche feature. section 8.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains generator syntax, next(), yield suspension, iterator results, two-way values, delegation, and async-iterator use.
Examples
Demonstrates infinite random numbers, a two-way multiplier, delegated names, and yielding fetch promises.
What it assumes
Builds on function syntax and establishes iterables as groundwork for understanding generator return values.
What you can do after
Apply generators to produce iterable sequences, suspend and resume execution, exchange values through next(), and delegate with yield*.
How it connects
Connects generators to iterables, iterators, async functions, async/await, and for await...of.

Also explained in

Compare how 13 books explain generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.