Docs
13.5-Generators
17.5 Generators
Overview
Generators are special functions that can pause execution and resume later, yielding multiple values over time. They provide a powerful way to create iterators and handle asynchronous operations.
Generator Syntax
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Generator Function ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ā
ā // Generator function declaration ā
ā function* generatorName() { ā
ā yield value1; ā
ā yield value2; ā
ā return finalValue; ā
ā } ā
ā ā
ā // Generator method in object ā
ā const obj = { ā
ā *generator() { ā
ā yield 1; ā
ā } ā
ā }; ā
ā ā
ā // Generator method in class ā
ā class MyClass { ā
ā *generator() { ā
ā yield 1; ā
ā } ā
ā } ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
How Generators Work
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Generator Execution ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ā
ā function* counter() { const gen = counter(); ā
ā console.log('Start'); ā
ā yield 1; āāā gen.next() ā {value: 1, done: false} ā
ā console.log('After 1'); // 'Start' printed ā
ā yield 2; āāā gen.next() ā {value: 2, done: false} ā
ā console.log('After 2'); // 'After 1' printed ā
ā return 3; āāā gen.next() ā {value: 3, done: true} ā
ā } // 'After 2' printed ā
ā gen.next() ā {value: undefined, done} ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
yield vs return
| Feature | yield | return |
|---|---|---|
| Pauses execution | Yes | No (terminates) |
| Resumes | Yes | No |
done property | false | true |
| Can be multiple | Yes | Only one (last) |
Generator Methods
const gen = myGenerator();
gen.next(value); // Resume execution, optionally pass value
gen.return(value); // Terminate generator with value
gen.throw(error); // Throw error at current yield
yield* Delegation
function* delegating() {
yield* [1, 2, 3]; // Delegate to array
yield* 'abc'; // Delegate to string
yield* otherGenerator(); // Delegate to another generator
}
Use Cases
- ā¢Custom iterators - Simplified iterator creation
- ā¢Lazy evaluation - Generate values on demand
- ā¢Infinite sequences - Memory-efficient streams
- ā¢State machines - Manage complex state
- ā¢Async flow control - With async generators
Generators Are Iterables
function* gen() {
yield 1;
yield 2;
}
for (const value of gen()) {
console.log(value); // 1, 2
}
console.log([...gen()]); // [1, 2]
Summary
- ā¢Generators use
function*syntax - ā¢
yieldpauses and returns a value - ā¢
next()resumes execution - ā¢Generators are iterables
- ā¢
yield*delegates to other iterables - ā¢Great for lazy sequences and iterators