Generators and Lazy Evaluation
A generator function is declared using function* and can pause execution with yield. Calling a generator function returns a generator object rather than immediately executing the entire body.
Generators are useful for lazy sequences, custom iteration, and controlling incremental computation. They can also receive values through subsequent next(value) calls.
A Generator Sequence
function* ids() {
let id = 1;
while (true) {
yield id++;
}
}
const iterator = ids();
console.log(iterator.next().value);
console.log(iterator.next().value);💡 The generator pauses at each yield. Each call to next resumes it until another yield or completion.
Key Takeaways
- Generators pause and resume execution.
- Generator functions return iterator-like generator objects.
- Generators enable lazy computation.
Knowledge Check
What does calling a generator function return?