JS Generators
In this page:
What Is a Generator?
A generator is a special function that can pause and continue later. It is declared with an asterisk. Unlike a normal function that runs to completion, a generator's execution can be suspended mid-function and resumed exactly where it left off.
Example: What Is a Generator?
function* numberGenerator() {
yield 1;
yield 2;
}
const gen = numberGenerator();
console.log(gen.next());
yield
yield pauses a generator and sends a value to the caller. The next() method continues from that point. Calling gen.next() runs the generator up to the next yield (or to the end), returning { value, done } — this makes generators a controllable, step-by-step source of values.
Example: yield
function* counter() {
yield 1;
yield 2;
}
const gen = counter();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: undefined, done: true }
Generator Iteration
Generators are iterable. A for...of loop can read their yielded values. This means you can iterate a generator's output the same way you'd iterate an array, without first collecting every value into memory.
Example: Generator Iteration
function* colors() {
yield "red";
yield "green";
}
for (const color of colors()) {
console.log(color);
}
Sending Values
next() can send a value back into a paused generator. This lets generators communicate with the caller. You can also pass a value into next(value), which becomes the result of the paused yield expression inside the generator, enabling two-way communication.
Example: Sending Values
function* echo() {
const received = yield "ready";
console.log("Got:", received);
}
const gen = echo();
console.log(gen.next());
gen.next("hello");
Practical Use
Generators are useful for controlled sequences, custom iterables, and lazy data processing. Because a generator computes each value only when asked, it's a natural fit for infinite sequences or expensive computations you only want to run as far as actually needed.
Example: Practical Use
function* infiniteCount() {
let n = 1;
while (true) yield n++;
}
const gen = infiniteCount();
console.log(gen.next().value, gen.next().value, gen.next().value);
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: