A generator function in JavaScript is a special type of function that can be paused and resumed, allowing it to yield multiple values over time instead of returning a single value. It is defined using the function* syntax. When called, a generator function returns a generator object, which can be used to control the execution of the function.
Here are some key features of generator functions:
- Yielding Values: Instead of using
return, generator functions use theyieldkeyword to produce a value and pause execution. - Stateful: The function maintains its state between invocations, allowing it to remember where it left off.
- Iteration: Generator functions can be iterated using a
for...ofloop or by calling thenext()method on the generator object.
Here’s a simple example of a generator function:
function* countUpTo(max) {
let count = 1;
while (count <= max) {
yield count;
count++;
}
}
const counter = countUpTo(5);
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
In this example, the countUpTo generator function yields numbers from 1 to the specified maximum value. Each call to next() retrieves the next value in the sequence.
