
Generator functions are a special kind of function in JavaScript that can be paused and resumed, allowing you to produce a sequence of values over time. They are defined using the `function*` syntax and use the `yield` keyword to 'pause' and return a value.
How They Work
When you call a generator function, it doesn't run the code. Instead, it returns a special object called a Generator. This object has a `.next()` method. When you call `.next()`, the function executes until it hits a `yield` statement, pauses, and returns an object like `{ value: 'some-value', done: false }`.
Example: A Simple ID Generator
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
The `while(true)` loop doesn't freeze the program because the generator pauses at each `yield` statement, waiting for the next call to `.next()`.
Generators and Iterables
Generators are iterable, which means you can use them with `for...of` loops.
function* numberGenerator() {
yield 10;
yield 20;
yield 30;
}
for (const num of numberGenerator()) {
console.log(num);
}
// Output:
// 10
// 20
// 30
Generators are a powerful tool for working with sequences of data, especially when the data is large or expensive to compute, as they produce values on demand.
Comments
Post a Comment