Generators
Generators
Section titled “Generators”Introduction
Section titled “Introduction”Generators are special functions that can be paused and resumed. They use the function* syntax and the yield keyword to produce sequences lazily.
Learning Objectives
Section titled “Learning Objectives”- Write generator functions with
function*andyield - Understand lazy evaluation
- Use
yield*for delegation - Create async generators
- Use generators for state machines and infinite sequences
Visual Summary
Section titled “Visual Summary”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 }Topics Covered
Section titled “Topics Covered”| Topic | Description | Est. Time |
|---|---|---|
| Generator Functions | function*, yield, next() | 15 min |
| yield | yield* delegation, passing values | 15 min |
| Async Generators | for await…of, async generator functions | 10 min |
Prerequisites
Section titled “Prerequisites”- Iterators and the iteration protocol
- Functions and execution context
- Async/await basics
Learning Path
Section titled “Learning Path”Generator Functions → yield → Async Generators