Generators are special functions that can be paused mid-execution, allowing other code to run in the meantime, and then resumed from where they were paused. They are powerful for writing custom iterators and handling asynchronous streams.
Generator Syntax
A generator function is declared with an asterisk (function*) and uses the yield keyword to return values sequentially.
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator(); // Returns a generator object
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
Infinite Streams
Because generators evaluate expressions lazily, they can generate infinite sequences without running out of memory:
function* infiniteIds() {
let id = 1;
while (true) {
yield id++;
}
}
const ids = infiniteIds();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2