Generators
A generator is a special function that can pause in the middle and resume later, producing a sequence of values over time. You declare it with function* and pause it with yield. Calling a generator function doesn't run its body; it returns a generator object, which is an iterator: each call to next() runs the body until the next yield and hands out that value. Generators are the easiest way to write iterators, they make lazy and infinite sequences natural, and their async version (async function* with for await) is the standard way to consume paginated APIs and streams.
In One Minute
function* name() { yield 1; yield 2; }: calling it returns a generator object (an iterator); the body hasn't run yet.- Each
next()runs until the nextyield, returning{ value, done: false }; at the end,{ value: returnValue, done: true }. - Generators are iterable, so
for...of, spread and destructuring work on them. yield*delegates to another iterable;next(value)sends a value back in as the result ofyield.async function*plusfor await...ofproduce and consume asynchronous sequences.
Defining and Running a Generator
Syntax
function* name(params) {
yield value1;
yield value2;
return finalValue; // optional
}
const gen = name(args); // doesn't run the body yet
gen.next(); // runs to the first yieldExample
function* paymentSteps() {
console.log(" (validating)");
yield "validated";
console.log(" (charging)");
yield "charged";
console.log(" (emailing)");
return "receipt sent";
}
const steps = paymentSteps();
console.log("created; nothing has run");
console.log(steps.next());
console.log(steps.next());
console.log(steps.next());
console.log(steps.next());created; nothing has run
(validating)
{ value: 'validated', done: false }
(charging)
{ value: 'charged', done: false }
(emailing)
{ value: 'receipt sent', done: true }
{ value: undefined, done: true }Explanation: creating the generator ran nothing. Each next() resumed the body from where it paused and ran until the next yield (or the end), so the logs interleave with the results. The return value appears once with done: true; after that, the generator is finished.
Generators as Iterators
A generator object is an iterator and an iterable, so all the iteration features from the previous lesson work. This makes generators the simplest way to make something iterable:
function* range(start, end, step = 1) {
for (let i = start; i <= end; i += step) yield i;
}
console.log([...range(9, 12)]);
for (const month of range(1, 12, 3)) console.log("quarter starts in month", month);
const [a, b] = range(100, 200, 50);
console.log(a, b);
class FeeSchedule {
constructor(base, step) { this.base = base; this.step = step; }
*[Symbol.iterator]() {
for (const grade of range(9, 12)) yield { grade, fee: this.base + (grade - 9) * this.step };
}
}
console.log([...new FeeSchedule(400, 15)].map((r) => r.fee));[9, 10, 11, 12]
quarter starts in month 1
quarter starts in month 4
quarter starts in month 7
quarter starts in month 10
100 150
[400, 415, 430, 445]Compare *[Symbol.iterator]() with the hand-written next() object in the previous lesson: the generator keeps its position (the loop variable) automatically, with no state object to manage. Note that for...of ignores the return value: only yielded values are iterated.
Lazy and Infinite Sequences
Because a generator computes each value only when asked, it can describe an infinite sequence safely, as long as the consumer stops:
function* receiptNumbers(start = 1001) {
let n = start;
while (true) yield `R-${n++}`;
}
function* take(iterable, count) {
if (count <= 0) return;
for (const item of iterable) {
yield item;
if (--count === 0) return;
}
}
const numbers = receiptNumbers();
console.log([...take(numbers, 3)]);
console.log(numbers.next());['R-1001', 'R-1002', 'R-1003']
{ value: undefined, done: true }The while (true) loop never runs away: each step happens only when the consumer calls next(). Notice the last line, though: numbers is finished, not paused at R-1004. When the for...of loop inside take stopped early, it called the source generator's return() method, closing it (the cleanup behavior shown later in this lesson). To keep using a generator after a partial loop, step it with next() yourself instead of for...of. (Built-in iterator helpers provide take for you; see the next lesson.)
yield*: Delegating
yield* yields every value from another iterable (an array, a string, another generator), as if each were yielded one by one:
function* fall() { yield "Tuition"; yield "Books"; }
function* spring() { yield "Tuition"; yield* ["Lab", "Field trip"]; }
function* schoolYear() {
yield "--- Fall";
yield* fall();
yield "--- Spring";
yield* spring();
}
console.log([...schoolYear()].join(" | "));
function* walk(node, depth = 0) {
yield `${" ".repeat(depth)}${node.name}`;
for (const child of node.children ?? []) yield* walk(child, depth + 1);
}
const tree = { name: "Fees", children: [{ name: "Tuition" }, { name: "Supplies", children: [{ name: "Books" }] }] };
console.log([...walk(tree)].join("\n"));--- Fall | Tuition | Books | --- Spring | Tuition | Lab | Field trip
Fees
Tuition
Supplies
BooksRecursive yield* is an elegant way to walk trees lazily: the consumer can stop at any point without the whole tree being processed.
Two-Way Communication
yield is an expression: the value passed to the next next(value) call becomes the result of the paused yield. That lets the caller send data into the generator:
function* runningTotal() {
let total = 0;
while (true) {
const amount = yield total;
if (typeof amount === "number") total += amount;
}
}
const tracker = runningTotal();
tracker.next();
console.log(tracker.next(120).value);
console.log(tracker.next(85).value);
console.log(tracker.next(45).value);120
205
250Explanation: the first next() starts the generator and runs it to the first yield total (yielding 0). Each later next(amount) resumes it with amount as the result of that yield, adds it, and pauses again at the next yield, sending back the new total.
Generators also have return(value), which finishes the generator early (running any finally blocks), and throw(error), which throws the error at the paused yield. Before async/await, libraries used exactly this two-way mechanism to write async code that looked synchronous.
Cleanup with try...finally
When a consumer stops early (break), the generator's return() is called, which runs any pending finally block, making cleanup automatic:
function* readRows(rows) {
console.log("cursor opened");
try {
for (const row of rows) yield row;
} finally {
console.log("cursor closed");
}
}
for (const row of readRows(["Navika", "Srihitha", "Advitha"])) {
console.log(row);
if (row === "Srihitha") break;
}cursor opened
Navika
Srihitha
cursor closedAsync Generators and for await
An async generator (async function*) can await inside and yield values that arrive over time. Consume it with for await...of, which awaits each value. This is the standard pattern for paginated APIs:
const pages = [["Navika", "Srihitha"], ["Advitha"], []];
const fetchPage = (n) => new Promise((resolve) => setTimeout(() => resolve(pages[n] ?? []), 10));
async function* allStudents() {
for (let page = 0; ; page++) {
const batch = await fetchPage(page);
if (batch.length === 0) return;
yield* batch;
}
}
for await (const name of allStudents()) {
console.log("student:", name);
}
const first = [];
for await (const name of allStudents()) {
first.push(name);
if (first.length === 1) break;
}
console.log("only fetched what was needed:", first);student: Navika
student: Srihitha
student: Advitha
only fetched what was needed: ['Navika']The consumer sees one simple stream of students and doesn't know about pages. Breaking out early stops further page requests. for await also works on Node.js streams and on arrays of promises; Array.fromAsync(asyncIterable) (ES2026) collects an async iterable into an array.
In Practice
The Fee Tracker generates a monthly payment schedule lazily: a generator yields each due date with Temporal, a second generator skips months already paid, and the consumer takes only the next three:
function* dueDates(firstDue) {
let date = Temporal.PlainDate.from(firstDue);
while (true) {
yield date;
date = date.add({ months: 1 });
}
}
function* unpaid(dates, paidMonths) {
for (const d of dates) {
if (!paidMonths.has(d.toPlainYearMonth().toString())) yield d;
}
}
const paid = new Set(["2026-09", "2026-10"]);
const next3 = [];
for (const d of unpaid(dueDates("2026-09-05"), paid)) {
next3.push(d.toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric" }));
if (next3.length === 3) break;
}
console.log(next3);['Nov 5, 2026', 'Dec 5, 2026', 'Jan 5, 2027']The infinite sequence of due dates is filtered and cut off lazily, so only the months actually needed are ever computed.
Common Mistakes
Expecting the body to run when the function is called. It runs only on next() (or iteration).
Forgetting the *. function gen() { yield 1; } is a SyntaxError, because yield only works inside generators.
Spreading an infinite generator. [...receiptNumbers()] never ends. Use take or break.
Expecting for...of to include the return value. Only yielded values are iterated.
Under the Hood
A generator is a function whose execution context can be suspended and resumed. Calling it creates a generator object holding a suspended context (its local variables, its position in the code, its scope chain) without running anything. next(value) pushes that context back onto the call stack, resumes it at the paused yield (which evaluates to value), and runs until the next yield, where the context is popped off the stack and saved again. Engines implement this by compiling generator functions into resumable state machines: V8 saves the interpreter's registers into the generator object at each yield and restores them on resume. async functions are built on the same machinery: an await is essentially a yield of a promise, with the engine (rather than your code) calling next when the promise settles.
Interview Corner
What is a generator in JavaScript?
A function declared with function* that can pause at yield and resume later. Calling it returns a generator object, which is both an iterator and an iterable; each next() runs the body to the next yield and returns { value, done }. Generators make custom iterators, lazy and infinite sequences, and coroutine-style flows easy.
What is the difference between yield and yield*?
yield value produces one value. yield* iterable delegates to another iterable or generator, producing each of its values in turn, and evaluates to the delegated generator's return value.
What does this print?
Show solution
function* g() {
const x = yield 1;
const y = yield x * 2;
return x + y;
}
const it = g();
console.log(it.next(5).value, it.next(10).value, it.next(3).value, it.next().done);1 20 13 trueThe first next(5) starts the generator; its argument is ignored because no yield is waiting. next(10) makes x 10 and yields 20. next(3) makes y 3 and returns 13.
Practice
Challenge: Write a generator chunk(array, size) that yields consecutive slices of size items, and use it to process 7 payments in groups of 3.
Show solution
function* chunk(array, size) {
for (let i = 0; i < array.length; i += size) yield array.slice(i, i + size);
}
const payments = [120, 85, 45, 200, 60, 30, 90];
for (const group of chunk(payments, 3)) {
console.log(group, "subtotal", group.reduce((a, b) => a + b, 0));
}[120, 85, 45] subtotal 250
[200, 60, 30] subtotal 290
[90] subtotal 90Key Takeaways
| Task | Code |
|---|---|
| Define | function* gen() { yield 1; } |
| Make a class iterable | *[Symbol.iterator]() { yield ...; } |
| Delegate | yield* otherIterable |
| Send a value in | gen.next(value) |
| Async sequence | async function* pages() { yield await fetch... } |
| Consume async | for await (const x of pages()) { ... } |
Was this tutorial helpful?