JavaScript Generators: function*, yield, yield*, Infinite Sequences and Recursive Generators
Generators made clear: what function* and yield do, how a generator pauses and resumes, generator objects as iterators, iterable classes in one line, infinite and lazy sequences, yield* for delegation and recursion (tree walking, flattening), return values, and common mistakes.
kvi5hnuCode Sprout team member5 min readOn this page
Article 90 built iterators by hand: an object with a next() method that tracks its own position and returns { value, done } objects. It works, but it's verbose. Generators write the same thing as an ordinary-looking function: you write a loop and yield each value, and JavaScript builds the iterator for you.
function* and yield
A generator function is declared with function*. Calling it doesn't run its body. Instead it returns a generator object, which is an iterator. Each call to next() runs the body until the next yield, pauses there, and hands the yielded value back:
function* trafficLight() {
console.log(" (body starts)");
yield "green";
yield "yellow";
yield "red";
}
const light = trafficLight();
console.log("created");
console.log(light.next());
console.log(light.next().value, light.next().value);
console.log(light.next());
created
(body starts)
{ value: 'green', done: false }
yellow red
{ value: undefined, done: true }

Note that "created" prints before "(body starts)": the body doesn't run until the first next(). Between calls, the generator is suspended, with its local variables and its position intact. That's the superpower: a function that can pause in the middle and continue later.
Generators are iterable
Generator objects implement the iteration protocol, and their [Symbol.iterator]() returns themselves, so they work anywhere iterables do:
function* trafficLight() {
yield "green";
yield "yellow";
yield "red";
}
const light = trafficLight();
console.log(light[Symbol.iterator]() === light, Object.prototype.toString.call(light));
console.log([...trafficLight()].join(" > "));
for (const color of trafficLight()) console.log(color.toUpperCase());
const [first, second] = trafficLight();
console.log(first, second);
true [object Generator]
green > yellow > red
GREEN
YELLOW
RED
green yellow
Like other iterators, a generator object is one-shot (article 90). Call the generator function again for a fresh sequence: [...trafficLight()] twice works; spreading the same light object twice gives an empty second result.
Syntax forms
function* gen() { /* body */ } // declaration
const genExpr = function* () { /* body */ }; // expression
const obj = { *items() { /* body */ } }; // method shorthand
class Shelf { *[Symbol.iterator]() { /* body */ } } // class method, computed name
The * can sit next to function or the name (function *gen works too); the community style is function*. There are no generator arrow functions, and generator functions can't be called with new.
Iterable classes in one line
The biggest everyday win: compare this with the hand-written Countdown iterator in article 90.
class Shelf {
#books = [];
add(...books) {
this.#books.push(...books);
return this;
}
*[Symbol.iterator]() {
for (const book of this.#books) yield book.title;
}
}
const shelf = new Shelf().add({ title: "Dune" }, { title: "Emma" });
console.log([...shelf], Array.from(shelf).length);
for (const title of shelf) console.log("-", title);
[ 'Dune', 'Emma' ] 2
- Dune
- Emma
Each loop calls [Symbol.iterator](), which creates a fresh generator, so the shelf can be iterated any number of times.
Practical generators
Ranges
JavaScript has no built-in range, but a generator makes one in three lines:
function* range(start, end, step = 1) {
for (let i = start; step > 0 ? i < end : i > end; i += step) yield i;
}
console.log([...range(0, 5)], [...range(10, 0, -3)], [...range(0, 1, 0.25)]);
[ 0, 1, 2, 3, 4 ] [ 10, 7, 4, 1 ] [ 0, 0.25, 0.5, 0.75 ]
Infinite sequences
Because values are produced on demand, a generator can run forever as long as the consumer stops:
function* ids(prefix = "id") {
let n = 1;
while (true) yield `${prefix}-${n++}`;
}
const orderIds = ids("ord");
console.log(orderIds.next().value, orderIds.next().value, ids().next().value);
function* fibonacci() {
let [a, b] = [0, 1];
for (;;) {
yield a;
[a, b] = [b, a + b];
}
}
function* take(n, iterable) {
if (n <= 0) return;
for (const x of iterable) {
yield x;
if (--n <= 0) return;
}
}
console.log([...take(8, fibonacci())]);
ord-1 ord-2 id-1
[
0, 1, 1, 2,
3, 5, 8, 13
]
while (true) inside a generator isn't a bug: the loop pauses at every yield. But never spread an infinite generator ([...fibonacci()]): it keeps asking for values until memory runs out. Always limit it with something like take, a break, or the built-in iterator helpers (fibonacci().take(8).toArray(), article 93).
Lazy pipelines
Each value flows through the whole chain before the next one is computed, and only as many values as needed are produced:
function* readings() {
for (const n of [3, 9, 14, 2, 20]) {
console.log(" reading", n);
yield n;
}
}
for (const value of readings()) {
if (value > 10) {
console.log("first above 10:", value);
break;
}
}
reading 3
reading 9
reading 14
first above 10: 14
The readings 2 and 20 are never produced.
yield*: delegating to another iterable
yield* iterable yields every value from another iterable, as if you'd written a for...of loop with yield inside:
function* concat(...iterables) {
for (const it of iterables) yield* it;
}
console.log([...concat("ab", [1, 2], new Set(["x"]))]);
[ 'a', 'b', 1, 2, 'x' ]
Recursive generators
yield* can delegate to another call of the same generator, which makes recursive structures easy to walk lazily:
const folders = {
name: "root",
children: [
{ name: "src", children: [{ name: "app.js", children: [] }] },
{ name: "README.md", children: [] },
],
};
function* walk(node, depth = 0) {
yield " ".repeat(depth) + node.name;
for (const child of node.children) yield* walk(child, depth + 1);
}
for (const line of walk(folders)) console.log(line);
function* flatten(items) {
for (const item of items) {
if (Array.isArray(item)) yield* flatten(item);
else yield item;
}
}
console.log([...flatten([1, [2, [3, [4]]], 5])]);
root
src
app.js
README.md
[ 1, 2, 3, 4, 5 ]
This is the cleanest way to write tree traversals (DOM nodes, file systems, JSON, ASTs) and permutation or combination generators, which are common interview exercises.
Return values
A generator can return a value. It appears in the final result object (done: true), but for...of and spread ignore it:
function* task() {
yield "step 1";
return "finished";
}
console.log([...task()]);
const t = task();
console.log(t.next(), t.next(), t.next());
function* outer() {
const result = yield* inner(); // yield* evaluates to inner's return value
yield `inner returned ${result}`;
}
function* inner() {
yield "inner work";
return 42;
}
console.log([...outer()]);
[ 'step 1' ]
{ value: 'step 1', done: false } { value: 'finished', done: true } { value: undefined, done: true }
[ 'inner work', 'inner returned 42' ]
Use return to end a generator early (if (n <= 0) return;). Rely on a returned value only when you call next() yourself or use yield*.
Common mistakes
yield inside a callback. yield only works directly in the generator's body, not in nested regular or arrow functions:
function* broken(list) {
// list.forEach((x) => { yield x; }); // SyntaxError: yield isn't allowed in the arrow function
}
function* fixed(list) {
for (const x of list) yield x; // use a loop (or yield* list)
}
Forgetting to call the generator. for (const x of gen) fails with "gen is not iterable"; you need gen().
Reusing a generator object. Store the generator function, or an iterable object whose [Symbol.iterator] is a generator, rather than a single generator object you plan to loop over twice.
Expecting the body to run on creation. Validation or side effects at the top of a generator don't happen until the first next(). If you want arguments checked immediately, use a regular function that validates and then returns a generator.
Common questions
When should I use a generator instead of returning an array?
When the sequence is large, infinite, expensive to compute, or likely to be consumed only partially. For a small list you'll use in full, returning an array is simpler, and array methods are fast.
Are generators slow?
They have some overhead per value compared with a plain loop, but modern engines optimize them well. Avoid them only in measured hot paths; their clarity usually wins.
Can a generator be async?
Yes. async function* creates an async generator that can await inside and is consumed with for await...of. It's covered with asynchronous JavaScript in Part 13.
What's the difference between yield and yield*?
yield value produces one value. yield* iterable produces every value of the iterable in turn (and evaluates to the delegate's return value).
Summary
function*declares a generator function; calling it returns a paused generator object without running the body.- Each
next()runs the body to the nextyieldand returns{ value, done: false }; finishing returns{ value: returnValue, done: true }. - Generator objects are one-shot iterators and work with
for...of, spread and destructuring. *[Symbol.iterator]() { ... }makes a class iterable in one method.- Generators are lazy, so they can represent infinite sequences; limit them before spreading.
yield*delegates to another iterable, enabling recursive traversals.yieldcan't appear inside nested callbacks; generators can't be arrows or constructors.
Practice Questions
What does this print?
function* g() {
console.log("A");
yield 1;
console.log("B");
}
const it = g();
console.log("C");
it.next();
it.next();
Answer
C, A, B. The body starts at the first next() and resumes after yield 1 on the second.
Write a generator cycle(items) that repeats the items forever: "a", "b", "a", "b", ....
Answer
function* cycle(items) {
if (items.length === 0) return;
while (true) yield* items;
}
The guard prevents an infinite loop that yields nothing.
What does this expression produce?
[...(function* () { yield 1; yield* [2, 3]; return 4; })()]
Answer
[1, 2, 3]. yield* yields each element of the array, and spread ignores the return value 4.
Write a recursive generator permutations(arr) that yields every ordering of an array's elements.
Answer
function* permutations(arr) {
if (arr.length <= 1) {
yield arr;
return;
}
for (let i = 0; i < arr.length; i++) {
const rest = [...arr.slice(0, i), ...arr.slice(i + 1)];
for (const p of permutations(rest)) yield [arr[i], ...p];
}
}
[...permutations([1, 2, 3])] has 6 entries.
Previous: JavaScript Iterators and Iterables: Symbol.iterator, the Iteration Protocol and Custom Iterables

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.