Loading...
Loading...
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.
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 }
yield — keyword that pauses execution and returns value..next() — resumes execution from the last yield.done: true — indicates generator is finished.| Feature | Regular Functions | Generators |
|---|---|---|
| Returning values | Only one return | Many yield |
| Intermediate states | No | Yes |
| Flow control | No | Yes |
Using for..of | No | Yes |
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
}
Useful for:
async/await appeared.