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












