Skip to content

Generators

Generators are special functions that can be paused and resumed. They use the function* syntax and the yield keyword to produce sequences lazily.

  • Write generator functions with function* and yield
  • Understand lazy evaluation
  • Use yield* for delegation
  • Create async generators
  • Use generators for state machines and infinite sequences
sequenceDiagram
participant Code as Caller
participant Gen as Generator
Code->>Gen: generator.next()
Note over Gen: Runs until yield
Gen->>Code: { value: 1, done: false }
Code->>Gen: generator.next()
Note over Gen: Resumes, runs to next yield
Gen->>Code: { value: 2, done: false }
Code->>Gen: generator.next()
Note over Gen: Resumes, function ends
Gen->>Code: { value: undefined, done: true }
TopicDescriptionEst. Time
Generator Functionsfunction*, yield, next()15 min
yieldyield* delegation, passing values15 min
Async Generatorsfor await…of, async generator functions10 min
  • Iterators and the iteration protocol
  • Functions and execution context
  • Async/await basics
Generator Functions → yield → Async Generators