JavaScript Generators Explained: yield, next() and 10 Examples
JavaScript generators are functions that can pause at yield and resume later, producing values one at a time. Learn how next() drives them, infinite and lazy sequences, two-way communication, yield*, cleanup with return(), async generators for paged APIs, and what they cost in speed, all run in Node.js.
- JavaScript generators are declared with
function*and pause at eachyield. - Calling one runs no code; each
next()runs until the nextyieldand returns{ value, done }. - They make infinite and lazy sequences easy: our pipeline squared, filtered and took 5 items from an endless stream.
- They are slower than plain loops for raw number crunching (70.4 ms vs 3.8 ms for a million items), so use them for clarity and laziness, not speed.
Most functions run from top to bottom and return once. A generator can stop halfway, hand a value to its caller, and continue later exactly where it left off, keeping all its local variables. That one ability makes JavaScript generators the cleanest tool for custom iterators, infinite sequences, lazy data pipelines, tree traversal and paging through APIs.
All ten examples ran in Node.js v24.22.1 as an ES module, and the output is shown as printed. Generators work the same way in every modern browser. If iterators are new, our array methods guide covers the related for...of basics.
What is a generator in JavaScript?
A generator function is declared with an asterisk, function*. Calling it does not run its body. Instead it returns a generator object, which is an iterator: it has a next() method, and it can be used with for...of, spread syntax and destructuring. Each next() call resumes the function until it reaches yield, which pauses it and passes out a value.
Example 1: pausing and resuming with yield
function* count3() {
console.log(" start");
yield 1;
console.log(" after 1");
yield 2;
yield 3;
return "done";
}
const g = count3();
console.log("created, nothing ran yet");
console.log(g.next()); // logs "start", then { value: 1, done: false }
console.log(g.next()); // logs "after 1", then { value: 2, done: false }
console.log(g.next()); // { value: 3, done: false }
console.log(g.next()); // { value: 'done', done: true }
console.log(g.next()); // { value: undefined, done: true }
Our run printed “created, nothing ran yet” before “start”, proving the body only begins on the first next(). The return value appears once with done: true; after that, every call returns undefined.
Example 2: spread and for…of
console.log([...count3()].join(",")); // 1,2,3
Spread and for...of call next() for you until done is true. Note that the return value, "done", is not included: iteration ignores it and only collects yielded values. If you need the final value, call next() manually or use yield*, shown in example 6.
Example 3: infinite sequences
function* ids() {
let i = 1;
while (true) yield i++;
}
const it = ids();
console.log(it.next().value, it.next().value, it.next().value); // 1 2 3
A while (true) loop would normally freeze your program, but here each yield pauses it, so values are produced only on demand. This is handy for ID generators, pagination cursors and simulations. Never spread an infinite generator, though: [...ids()] would run forever.
Example 4: lazy pipelines
function* take(n, src) { for (const x of src) { if (n-- <= 0) return; yield x; } }
function* map(f, src) { for (const x of src) yield f(x); }
function* filter(p, src) { for (const x of src) if (p(x)) yield x; }
console.log([...take(5, filter(x => x % 3 === 0, map(x => x * x, ids())))]);
// [ 9, 36, 81, 144, 225 ]
Array methods like map and filter build a full new array at every step. Generator pipelines pass one value at a time through all stages, so they work on infinite inputs and use constant memory. Here each number is squared, checked for divisibility by 3, and the pipeline stops after five results, without ever creating a big array.
Example 5: sending values into a generator
function* conv() {
const name = yield "What is your name?";
const age = yield `Hi ${name}, age?`;
return `${name} is ${age}`;
}
const c = conv();
console.log(c.next().value, "|", c.next("Asha").value, "|", c.next(30).value);
// What is your name? | Hi Asha, age? | Asha is 30
The argument of next(value) becomes the result of the paused yield expression. The first next() only starts the generator, so a value passed to it is ignored. This two-way flow is how libraries built async control flow on generators before async/await arrived, and it still powers state machines and step-by-step wizards. The strings use template literals.
Example 6: delegating with yield*
function* inner() { yield "a"; yield "b"; return "inner-result"; }
function* outer() {
const r = yield* inner();
yield `got ${r}`;
yield* [1, 2];
}
console.log([...outer()]); // [ 'a', 'b', 'got inner-result', 1, 2 ]
yield* hands control to another iterable until it finishes, passing its values straight through. The expression itself evaluates to the inner generator’s return value, which is how outer captured "inner-result". It also works with any iterable, such as arrays, strings, Maps and Sets.
Example 7: cleanup with finally and return()
function* withCleanup() {
try { yield 1; yield 2; yield 3; }
finally { console.log(" cleanup ran"); }
}
for (const x of withCleanup()) { if (x === 2) break; } // logs "cleanup ran"
const w = withCleanup();
w.next();
console.log(w.return(99)); // logs "cleanup ran", then { value: 99, done: true }
Breaking out of a for...of loop automatically calls the generator’s return() method, which runs any finally block. You can also call return(value) yourself to stop a generator early. Use this to close files, release locks or cancel timers when the consumer stops early.
Example 8: throwing errors into a generator
function* guarded() {
while (true) {
try { yield "ok"; }
catch (e) { console.log(" caught inside:", e.message); yield "recovered"; }
}
}
const gd = guarded();
gd.next();
console.log(gd.throw(new Error("boom")).value);
// logs "caught inside: boom", then recovered
throw(error) raises the error at the paused yield, as if that line had thrown. The generator can catch it and continue, or let it propagate to the caller. Combined with example 5, this lets a generator act like a small coroutine that both receives data and handles failures.
Example 9: making objects iterable
class Range {
constructor(a, b) { this.a = a; this.b = b; }
*[Symbol.iterator]() { for (let i = this.a; i < this.b; i++) yield i; }
}
console.log([...new Range(3, 7)]); // [ 3, 4, 5, 6 ]
const tree = { v: 1, kids: [{ v: 2, kids: [{ v: 4, kids: [] }] }, { v: 3, kids: [] }] };
function* walk(n) { yield n.v; for (const k of n.kids) yield* walk(k); }
console.log([...walk(tree)]); // [ 1, 2, 4, 3 ]
Writing an iterator by hand needs an object with next() and careful state. A generator method on Symbol.iterator does it in one line, and any class becomes usable with for...of and spread; see our JavaScript classes guide. Combining recursion with yield* gives a depth-first tree walk that produces nodes lazily.
Example 10: async generators for paged APIs
async function* pages() {
for (let p = 1; p <= 3; p++) {
await new Promise(r => setTimeout(r, 5)); // stand-in for fetch(`/api?page=${p}`)
yield { page: p, items: [p * 10, p * 10 + 1] };
}
}
const all = [];
for await (const pg of pages()) all.push(...pg.items);
console.log(all); // [ 10, 11, 20, 21, 30, 31 ]
An async function* can await inside and is consumed with for await...of. It is the natural way to stream paginated API results, read a file chunk by chunk, or process messages as they arrive. The consumer code stays a simple loop, and the next page is requested only when the loop asks for it. We simulated the network with a timer; see the fetch API guide for real requests.
Generators are single use
const g2 = count3();
console.log([...g2].length, [...g2].length); // 3 0
A generator object is exhausted after one pass; the second spread got nothing. If you need to iterate again, call the generator function again, or make your object iterable with Symbol.iterator as in example 9, which returns a fresh generator each time.
Tip: pass around the generator function or an iterable object, not a generator instance, when several consumers need the same sequence.
Iterator helpers
ids().filter(x => x % 2).map(x => x * 10).take(3).toArray();
// [ 10, 30, 50 ]
Recent JavaScript engines, including Node.js 24, support iterator helpers: map, filter, take, drop, flatMap, reduce and toArray directly on iterators. They do the same lazy work as our hand-written pipeline in example 4 with less code. Check browser support before relying on them in front-end code.
Performance: generators vs loops vs arrays
| Summing 1,000,000 numbers | Time |
|---|---|
Generator pipeline (take over ids()) |
70.4 ms |
Plain for loop |
3.8 ms |
Build an array, then for...of |
71.0 ms |
Each next() call and result object has overhead, so a generator was about 18 times slower than a plain counting loop in this single run. It was about as fast as first building a million-item array, while using far less memory. Use generators where laziness, readability or memory matter, and plain loops for tight numeric inner loops. The JavaScript event loop guide explains how async generators interleave with other work.
When to use generators
- Custom iterables and data structures.
- Infinite or very large sequences, generated on demand.
- Lazy multi-step pipelines over streams of data.
- Tree and graph traversal with
yield*. - Paged APIs and streams with async generators.
- Avoid them for simple arrays where
mapor reduce is clearer.
Final thoughts
JavaScript generators give functions a pause button. With function*, yield and next() you can build lazy pipelines, endless sequences, clean iterators, tree walkers and async page streams in a few readable lines, with return() and finally for cleanup. They cost some raw speed, so keep them out of hot numeric loops, but for expressing sequences they are hard to beat. Python developers will recognise the same ideas from Python generators.
Frequently asked questions
What is a generator function in JavaScript?
It is a function declared with function and an asterisk. Calling it returns an iterator, and each call to next runs the body until the next yield, returning an object with value and done.
What does yield do in JavaScript?
yield pauses the generator and sends a value to the caller. When next is called again, the generator resumes right after the yield, and the argument passed to next becomes the result of the yield expression.
What is the difference between yield and return in a generator?
yield pauses and can be used many times. return ends the generator, sets done to true and supplies a final value that for of loops and spread syntax ignore.
Can a generator be reused?
No. A generator object is exhausted after one full pass. Call the generator function again for a fresh one, or implement Symbol.iterator so each loop gets a new generator.
What is an async generator?
It is a generator declared with async function and an asterisk that can use await inside. You consume it with for await of, which makes it ideal for paged API results and streams.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.