JavaScript Generators: function* and yield Explained
Generators are functions that can pause their execution and resume it later. They give more control over execution flow, unlike regular functions.
Generators are defined using function* and controlled via the .next() method.
Generator Syntax
function* generatorFunction() {
yield 'First value';
yield 'Second value';
return 'Final';
}
const gen = generatorFunction();
console.log(gen.next()); // { value: 'First value', done: false }
console.log(gen.next()); // { value: 'Second value', done: false }
console.log(gen.next()); // { value: 'Final', done: true }
How Generator Works
yield— keyword that pauses execution and returns value..next()— resumes execution from the lastyield.done: true— indicates generator is finished.
Differences from Regular Functions
| Feature | Regular Functions | Generators |
|---|---|---|
| Returning values | Only one return | Many yield |
| Intermediate states | No | Yes |
| Flow control | No | Yes |
Using for..of | No | Yes |
Generators and Iterators
Generator is an iterator that follows the Iterable protocol. This allows using it in for...of loop.
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
for (const num of range(1, 5)) {
console.log(num); // 1, 2, 3, 4, 5
}
When to Use Generators?
Useful for:
- Working with data streams — e.g., generating sequences.
- Iterable structures — arrays, trees, graphs.
- Execution control — e.g., when manual step-by-step data processing is needed.
- Creating lazy evaluations.
- Simulating async behavior before
async/awaitappeared.