Advanced JavaScript Generators: Passing Values with next(), return(), throw(), Cleanup and State Machines
The other half of generators: yield as an expression, sending values in with next(value), why the first next() argument is ignored, ending a generator with return(), injecting errors with throw(), try/finally cleanup, delegation with yield*, and practical uses like state machines and tokenizers.
kvi5hnuCode Sprout team member6 min readOn this page
Article 91 used generators as easy iterators: values flow out through yield. But a generator is really a function that can pause and resume, and that makes it a two-way channel. The caller can send values in, force the generator to finish, or inject an error at the paused yield. These features are less common in everyday code, but they explain how libraries like Redux-Saga and co worked, how async/await was originally built, and they show up in advanced interviews.
yield is an expression
yield doesn't only send a value out; it also evaluates to something: the argument of the next() call that resumes it.
function* conversation() {
console.log(" started");
const name = yield "What's your name?";
const lang = yield `Hi ${name}! Favorite language?`;
return `${name} likes ${lang}`;
}
const chat = conversation();
console.log(chat.next("ignored").value);
console.log(chat.next("Ana").value);
console.log(chat.next("JavaScript"));
started
What's your name?
Hi Ana! Favorite language?
{ value: 'Ana likes JavaScript', done: true }

Trace it carefully, because the timing is the tricky part:
chat.next("ignored")starts the body. It runs to the firstyieldand sends out the question. There was no pausedyieldto receive"ignored", so the firstnext()argument is always discarded.chat.next("Ana")resumes the pausedyield, which evaluates to"Ana", soname = "Ana". The body runs to the secondyield.chat.next("JavaScript")makes the secondyieldevaluate to"JavaScript". The body returns, givingdone: true.
Because of step 1, generators that consume input are usually "primed" with one empty next() call first:
function* runningAverage() {
let total = 0;
let count = 0;
let average;
while (true) {
const value = yield average;
total += value;
count++;
average = total / count;
}
}
const avg = runningAverage();
avg.next(); // prime: run to the first yield
console.log(avg.next(10).value, avg.next(20).value, avg.next(60).value);
10 15 30
A generator that receives values and keeps state between them is often called a coroutine.
yield has very low precedence, so wrap it in parentheses inside larger expressions. yield + 1 means yield (+1) (it yields the number 1), and 2 * yield x is a syntax error; write (yield) + 1 and 2 * (yield x). As a function argument or on the right of =, no parentheses are needed: console.log("got", yield) is fine.
return(): finishing a generator early
generator.return(value) resumes the generator as if the paused yield were a return statement. The generator finishes and reports { value, done: true }. Crucially, any finally blocks run first:
function* counter() {
let n = 0;
try {
while (true) yield n++;
} finally {
console.log(" cleanup");
}
}
const c = counter();
console.log(c.next().value, c.next().value);
console.log(c.return("stopped"));
console.log(c.next());
for (const n of counter()) {
if (n === 2) break; // break calls return() automatically
}
0 1
cleanup
{ value: 'stopped', done: true }
{ value: undefined, done: true }
cleanup
This is the generator version of the iterator return() method from article 90, and it's why try...finally is the right place for cleanup in generators: it runs whether the generator finishes normally, a consumer breaks out of a loop, destructuring stops early, or an exception escapes.
A few edge cases:
- Calling
return()on a generator that hasn't started finishes it without running any body code:gen().return(7)gives{ value: 7, done: true }. - A
finallyblock can itselfyield, which delays completion. That's confusing; keepfinallyblocks to cleanup.
throw(): injecting an error
generator.throw(error) resumes the generator by throwing the error at the paused yield. If the generator catches it, it can recover and continue; otherwise the error propagates out of the throw() call and the generator is finished:
function* resilientCounter() {
let n = 0;
while (true) {
try {
yield n++;
} catch (err) {
console.log(" caught:", err.message, "- resetting");
n = 0;
}
}
}
const r = resilientCounter();
console.log(r.next().value, r.next().value, r.next().value);
console.log(r.throw(new Error("reset")).value, r.next().value);
function* fragile() {
yield 1;
yield 2;
}
const f = fragile();
f.next();
try {
f.throw(new Error("bad input"));
} catch (err) {
console.log("escaped:", err.message);
}
console.log(f.next());
0 1 2
caught: reset - resetting
0 1
escaped: bad input
{ value: undefined, done: true }
throw() returns the result of the next yield the generator reaches after handling the error. Here the counter caught the error, reset n, and yielded 0 again.
This mechanism is how promise-based runners were built before async/await: a runner called next(result) when a yielded promise fulfilled and throw(error) when it rejected, so try...catch inside the generator handled async errors. async functions do the same thing natively (Part 13).
Summary of generator methods
| Call | Resumes the paused yield as if it... | Returns |
|---|---|---|
next(value) | evaluated to value | the next { value, done } |
return(value) | were return value (finally blocks run) | { value, done: true } (unless finally yields) |
throw(error) | were throw error | the next result if the generator catches it; otherwise throws |
All three are defined on the generator prototype, and a finished generator ignores next() (always { value: undefined, done: true }). A generator can't be resumed while it's already running: calling next() on itself from inside its own body throws "Generator is already running".
yield* forwards everything
yield* doesn't only forward values. Calls to next(value), return() and throw() on the outer generator are passed through to the inner one while it's active, so cleanup in the inner generator still runs:
function* inner() {
try {
yield "i1";
yield "i2";
} finally {
console.log(" inner cleanup");
}
}
function* outer() {
yield* inner();
yield "after inner";
}
const o = outer();
console.log(o.next().value);
console.log(o.return("done"));
i1
inner cleanup
{ value: 'done', done: true }
Practical patterns
State machines
A generator's position is its state, so sequential flows (wizards, game turns, protocol handshakes) read top to bottom:
function* trafficLight() {
let state = "green";
while (true) {
const event = yield state;
if (event === "emergency") state = "red";
else state = { green: "yellow", yellow: "red", red: "green" }[state];
}
}
const light = trafficLight();
console.log(light.next().value, light.next("tick").value, light.next("emergency").value, light.next("tick").value);
green yellow red green
Tokenizers and parsers
A lexer that yields tokens lets the parser pull one token at a time, without first building an array of all tokens:
function* tokenize(source) {
let i = 0;
while (i < source.length) {
const ch = source[i];
if (ch === " ") {
i++;
} else if (ch >= "0" && ch <= "9") {
let j = i;
while (j < source.length && source[j] >= "0" && source[j] <= "9") j++;
yield { type: "number", value: Number(source.slice(i, j)) };
i = j;
} else {
yield { type: "operator", value: ch };
i++;
}
}
}
console.log([...tokenize("12 + 3*45")].map((t) => `${t.type}:${t.value}`).join(" "));
number:12 operator:+ number:3 operator:* number:45
Where advanced generators show up in practice
- Redux-Saga describes side effects as generators that
yieldeffect descriptions; the library callsnext(result)andthrow(error)to drive them. - Testing: a saga or coroutine can be stepped manually with
next()to check each yielded value, without running real I/O. - Async generators (
async function*, Part 13) combine pausing withawait, for streams and paginated APIs.
For ordinary async code, use async/await: using generators as a hand-rolled async runner is now historical.
Common questions
Why is the argument to the first next() ignored?
The first next() starts the body, and there's no paused yield yet to receive a value. Pass initial data as arguments to the generator function instead, or prime the generator with an empty next().
How do I make sure a generator releases resources?
Put the cleanup in try...finally inside the generator. It runs on normal completion, on return() (including break in for...of), and when an error propagates.
What happens if I call next() on a generator after throw() escaped it?
The generator is finished, so next() returns { value: undefined, done: true } forever.
Are generators the same as threads?
No. Only one piece of code runs at a time. A generator pauses only at yield, and only when the caller asks for the next value. That's cooperative, single-threaded control flow; real parallelism in JavaScript needs Web Workers or worker threads.
Summary
yieldis an expression: it evaluates to the argument of thenext()call that resumes it; the firstnext()argument is discarded.return(value)finishes a generator (runningfinallyblocks);for...ofcalls it onbreak.throw(error)raises an error at the pausedyield; the generator can catch it and continue, or it propagates to the caller.try...finallyis the reliable cleanup mechanism in generators;yield*forwardsnext,returnandthrowto the delegate.- Generators make good coroutines, state machines and tokenizers; for async code, prefer
async/await.
Practice Questions
What does this print?
function* g() {
const x = yield 1;
console.log("x =", x);
}
const it = g();
it.next("a");
it.next("b");
Answer
x = b. The first next("a") starts the body and its argument is discarded; next("b") resumes the yield, which evaluates to "b".
Write a generator idGenerator() that yields 1, 2, 3, ... and restarts from 1 when the caller calls next("reset").
Answer
function* idGenerator() {
let id = 1;
while (true) {
const cmd = yield id;
id = cmd === "reset" ? 1 : id + 1;
}
}
What's printed?
function* g() {
try {
yield 1;
} finally {
console.log("F");
}
}
for (const v of g()) {
console.log(v);
break;
}
Answer
1, then F. The break calls the generator's return(), which runs the finally block.
What does g.throw(new Error("x")) do if g was created but next() was never called?
Answer
The generator finishes without running any body code (no try is active yet), and the error is thrown out of the throw() call to the caller.
Previous: JavaScript Generators: function*, yield, yield*, Infinite Sequences and Recursive Generators
Next: JavaScript Iterator Helpers: map, filter, take, drop, flatMap and reduce on Any Iterator (ES2025)

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.