JavaScript Generators: function*, yield and Lazy Sequences
Learn JavaScript generators step by step: function*, yield, the generator object, next(value), yield* delegation, infinite sequences and async generators.
What you will learn
In the iterators lesson you learned how iteration works, and you wrote iterators by hand. It worked, but it was long: you had to keep the position in a variable, return { value, done } objects, and write helper after helper.
A generator is a special function that makes all of this almost effortless. It can pause in the middle, give a value to the outside, and later continue from the same place, with all its variables still alive. In this lesson you will learn function* and yield, how the generator object works, how to build lazy and infinite sequences, how to send values into a generator with next(value), how to stop one early with return() and throw(), how yield* delegates to other iterables, and a short preview of async generators. You will see that a generator is simply a ready-made iterator that you write like a normal function.
The problem: iterators are long to write
Here is the Fibonacci iterator from the last lesson:
const fibonacci = {
[Symbol.iterator]() {
let [a, b] = [0, 1];
return {
next() {
const value = a;
[a, b] = [b, a + b];
return { value, done: false };
}
};
}
};
And here is the same thing as a generator:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
for (const n of fibonacci()) {
if (n > 50) break;
console.log(n); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
}
No next(), no { value, done }, no hidden state object. Just a loop and a yield. Let us see how it works.
The idea in one line
A generator is a function that can pause at
yieldand resume later, remembering everything.
Think of a video with a pause button. Normal functions are like a video that plays from start to end without stopping. A generator is a video you can pause at any moment, and when you press play again, it continues from the exact second where it stopped. It remembers its place, and everything that was set up so far.
function* and yield
A generator function is written with a star: function*. Inside it, the keyword yield means: “pause here, and give this value to the caller.”
function* greet() {
yield "Hello";
yield "Namaste";
yield "Hola";
}
Calling a generator does NOT run it
This is the most important surprise. When you call a generator function, none of its code runs. You get back a generator object, a paused function waiting for your signal:
function* steps() {
console.log("Step 1 runs");
yield "first";
console.log("Step 2 runs");
yield "second";
console.log("Step 3 runs");
return "finished";
}
const gen = steps(); // nothing printed yet!
console.log("Generator created"); // "Generator created"
next(): run until the next yield
Every time you call gen.next(), the function resumes, runs until the next yield, then pauses again. Each call returns { value, done }, exactly like the iterator protocol.
console.log(gen.next());
// "Step 1 runs"
// { value: "first", done: false }
console.log(gen.next());
// "Step 2 runs"
// { value: "second", done: false }
console.log(gen.next());
// "Step 3 runs"
// { value: "finished", done: true } (the return value, and done is true)
console.log(gen.next());
// { value: undefined, done: true } (already finished)
Follow the story:
| Call | What happens |
|---|---|
steps() |
Creates the generator. No code runs. |
1st next() |
Runs from the top to the first yield. Pauses. |
2nd next() |
Resumes after the first yield, runs to the second yield. Pauses. |
3rd next() |
Resumes, reaches return. Done: { value: "finished", done: true }. |
4th next() |
Already done: { value: undefined, done: true }. |
Remember:
yieldpauses and gives a value.returnends the generator and gives a final value (withdone: true).
Ways to write generator functions
function* a() { yield 1; } // declaration
const b = function* () { yield 1; }; // expression
const object = {
*c() { yield 1; } // object method
};
class Shelf {
*d() { yield 1; } // class method
}
The star can sit next to function or next to the name. function* name() is the most common style. Two rules:
- There are no arrow generators.
*() => {}is aSyntaxError. - You cannot call a generator with
new.
(Also remember from the strict mode lesson that yield is a reserved word: you cannot use it as a variable name in strict mode.)
A generator object is an iterator, and an iterable
The object you get back follows both protocols from the iterators lesson:
- It has
next(), so it is an iterator. - Its
[Symbol.iterator]()returns itself, so it is also iterable.
function* letters() {
yield "a";
yield "b";
yield "c";
}
const gen = letters();
console.log(gen[Symbol.iterator]() === gen); // true
console.log(Object.prototype.toString.call(gen)); // "[object Generator]"
This means you can use it everywhere iterables work:
console.log([...letters()]); // ["a", "b", "c"]
console.log(Array.from(letters())); // ["a", "b", "c"]
console.log(new Set(letters()).size); // 3
const [first, second] = letters();
console.log(first, second); // "a" "b"
for (const letter of letters()) {
console.log(letter); // "a", "b", "c"
}
Like every iterator, a generator is used up after one pass:
const gen = letters();
console.log([...gen]); // ["a", "b", "c"]
console.log([...gen]); // [] (finished)
But each call to the generator function creates a brand-new, independent generator, with its own variables:
const one = letters();
const two = letters();
console.log(one.next().value); // "a"
console.log(one.next().value); // "b"
console.log(two.next().value); // "a" (two has its own position)
The state is remembered
A generator keeps its local variables alive between pauses, just like the closures you studied. This is why you do not need an outside index variable:
function* counter() {
let count = 0; // lives as long as the generator lives
while (true) {
count++;
yield count;
}
}
const c = counter();
console.log(c.next().value); // 1
console.log(c.next().value); // 2
console.log(c.next().value); // 3
Lazy and infinite sequences
A generator runs only when asked (lazy), so an endless while (true) loop is perfectly safe, as long as you stop taking values:
function* naturals() {
let n = 1;
while (true) {
yield n++;
}
}
const numbers = naturals();
console.log(numbers.next().value); // 1
console.log(numbers.next().value); // 2
console.log(numbers.next().value); // 3
Warning: do not use spread or
Array.fromon an infinite generator ([...naturals()]). It never ends and freezes the page. Usebreak, or atakehelper, to stop.
Small generator tools: take, map, filter
Remember the long helpers from the iterators lesson? Here they are with generators:
function* take(iterable, count) {
if (count <= 0) return;
let taken = 0;
for (const value of iterable) {
yield value;
if (++taken >= count) return;
}
}
function* map(iterable, fn) {
for (const value of iterable) {
yield fn(value);
}
}
function* filter(iterable, test) {
for (const value of iterable) {
if (test(value)) yield value;
}
}
Each one is only a few lines. Now chain them into a lazy pipeline:
// The first 5 doubled Fibonacci numbers that are divisible by 4
const result = take(
filter(
map(fibonacci(), (n) => n * 2),
(n) => n % 4 === 0
),
5
);
console.log([...result]); // [0, 4, 16, 68, 288]
Compare this with the iterators lesson: the same result, with about a quarter of the code. And it is still lazy: each value travels through the whole chain one at a time.
Some other tiny generators you will use again and again:
function* range(start, end, step = 1) {
for (let i = start; i <= end; i += step) {
yield i;
}
}
console.log([...range(1, 10, 3)]); // [1, 4, 7, 10]
function* chunk(iterable, size) {
let batch = [];
for (const value of iterable) {
batch.push(value);
if (batch.length === size) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch; // the leftover items
}
console.log([...chunk(range(1, 7), 3)]); // [[1, 2, 3], [4, 5, 6], [7]]
Sending values INTO a generator: next(value)
yield is not only a way to send values out. It is also an expression that receives a value. Whatever you pass to next(value) becomes the result of the yield the generator was paused on.
function* chat() {
const name = yield "What is your name?"; // pause, then receive name
const age = yield "Hi " + name + "! How old are you?";
return name + " is " + age + " years old";
}
const conversation = chat();
console.log(conversation.next().value); // "What is your name?"
console.log(conversation.next("Riya").value); // "Hi Riya! How old are you?"
console.log(conversation.next(21)); // { value: "Riya is 21 years old", done: true }
Walk through it slowly:
- The first
next()starts the generator and runs to the firstyield, which gives out the question. next("Riya")resumes. The pausedyieldnow becomes"Riya", sonameis"Riya". It runs to the nextyield.next(21)resumes again:agebecomes21, and the generator returns the final text.
Important: the value passed to the very first
next()is ignored, because there is no pausedyieldyet to receive it. The firstnext()only starts the generator.
A running average
function* runningAverage() {
let sum = 0;
let count = 0;
let average = 0;
while (true) {
const number = yield average; // give out the average, wait for a number
sum += number;
count++;
average = sum / count;
}
}
const avg = runningAverage();
avg.next(); // start it
console.log(avg.next(10).value); // 10
console.log(avg.next(20).value); // 15
console.log(avg.next(60).value); // 30
The generator remembers sum and count between calls, without any class or outside variable.
Stopping a generator: return() and throw()
A generator object has two more methods besides next().
return(value): finish early
gen.return(value) ends the generator immediately and gives back { value, done: true }:
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const gen = numbers();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.return("stop")); // { value: "stop", done: true }
console.log(gen.next()); // { value: undefined, done: true }
Cleanup with try...finally
Do you remember the iterator’s return() from the last lesson, which cleans up when a loop stops early? Generators do this automatically. Any finally block runs when the generator is closed early (by break, return(), destructuring, or an error):
function* openFile() {
console.log("File opened");
try {
yield "line 1";
yield "line 2";
yield "line 3";
} finally {
console.log("File closed"); // always runs
}
}
for (const line of openFile()) {
console.log(line);
if (line === "line 2") break; // the loop stops early
}
// "File opened"
// "line 1"
// "line 2"
// "File closed"
You get the cleanup logic for free, with no return() method to write (this uses the try/catch/finally from the error handling lesson).
throw(error): send an error into the generator
gen.throw(error) makes the paused yield throw that error. The generator can catch it with try...catch and keep going:
function* safeReader() {
while (true) {
try {
const value = yield;
console.log("Got:", value);
} catch (error) {
console.log("Caught inside:", error.message);
}
}
}
const reader = safeReader();
reader.next(); // start
reader.next("hello"); // "Got: hello"
reader.throw(new Error("bad data")); // "Caught inside: bad data"
reader.next("still alive"); // "Got: still alive"
If the generator does not catch the error, it travels out to the caller and the generator is finished.
yield*: delegate to another iterable
yield* (yield with a star) hands the work over to another iterable or generator, and yields all of its values, one by one.
function* inner() {
yield "b";
yield "c";
}
function* outer() {
yield "a";
yield* inner(); // yields "b", then "c"
yield "d";
}
console.log([...outer()]); // ["a", "b", "c", "d"]
yield* works with any iterable, such as arrays and strings:
function* mixed() {
yield* "hi"; // "h", "i"
yield* [1, 2]; // 1, 2
}
console.log([...mixed()]); // ["h", "i", 1, 2]
A common mistake:
yield inner()(without the star) yields the generator object itself, not its values. Useyield*to go inside.
The return value of a delegated generator
yield* is also an expression. Its value is the return value of the generator it delegated to:
function* inner() {
yield "b";
return "inner-finished";
}
function* outer() {
yield "a";
const result = yield* inner();
console.log("inner said:", result); // "inner said: inner-finished"
yield "c";
}
console.log([...outer()]); // ["a", "b", "c"]
Recursion: flatten a nested array
yield* makes recursive generators very short:
function* flatten(items) {
for (const item of items) {
if (Array.isArray(item)) {
yield* flatten(item); // go inside, however deep
} else {
yield item;
}
}
}
console.log([...flatten([1, [2, [3, 4]], 5])]); // [1, 2, 3, 4, 5]
Compare this with the iterators lesson, where flattening only two levels needed more than twenty lines.
Walking a tree
function* walk(node, depth = 0) {
yield " ".repeat(depth) + node.name;
for (const child of node.children ?? []) {
yield* walk(child, depth + 1);
}
}
const folders = {
name: "project",
children: [
{ name: "src", children: [{ name: "index.js" }, { name: "utils.js" }] },
{ name: "README.md" }
]
};
console.log([...walk(folders)].join("\n"));
// project
// src
// index.js
// utils.js
// README.md
Generators make custom iterables easy
The easiest way to make your own class iterable is a generator method named *[Symbol.iterator]().
Here is the linked list from the iterators lesson, with a three-line iterator:
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
const node = { value, next: null };
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) current = current.next;
current.next = node;
}
return this;
}
*[Symbol.iterator]() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
}
const list = new LinkedList().add("Riya").add("Karan").add("Aman");
console.log([...list]); // ["Riya", "Karan", "Aman"]
No next() method and no { value, done } object. And since every call to [Symbol.iterator]() creates a new generator, each loop gets its own position automatically.
You can also make a plain object iterable:
const user = {
name: "Riya",
city: "Delhi",
*[Symbol.iterator]() {
yield* Object.entries(this);
}
};
for (const [key, value] of user) {
console.log(key, value);
}
// "name Riya"
// "city Delhi"
// (the generator method is a symbol key, so it is not listed)
Real-life use cases
1. Unique IDs
function* idGenerator(prefix) {
let n = 1;
while (true) {
yield prefix + "-" + n++;
}
}
const userIds = idGenerator("user");
console.log(userIds.next().value); // "user-1"
console.log(userIds.next().value); // "user-2"
console.log(userIds.next().value); // "user-3"
2. Take turns forever (round robin)
function* cycle(items) {
while (true) {
yield* items;
}
}
const colors = cycle(["red", "green", "blue"]);
console.log(colors.next().value); // "red"
console.log(colors.next().value); // "green"
console.log(colors.next().value); // "blue"
console.log(colors.next().value); // "red" (starts again)
Handy for rotating banners, alternating row colors or load balancing.
3. A state machine (traffic light)
function* trafficLight() {
while (true) {
yield "green";
yield "yellow";
yield "red";
}
}
const light = trafficLight();
console.log(light.next().value); // "green"
console.log(light.next().value); // "yellow"
console.log(light.next().value); // "red"
console.log(light.next().value); // "green"
The generator is the state: it remembers which light comes next. A multi-step form or wizard can work the same way.
4. Show data in pages
function* paginate(items, pageSize) {
for (let start = 0; start < items.length; start += pageSize) {
yield items.slice(start, start + pageSize);
}
}
const products = ["Pen", "Book", "Bag", "Cap", "Bottle"];
const pages = paginate(products, 2);
console.log(pages.next().value); // ["Pen", "Book"]
console.log(pages.next().value); // ["Bag", "Cap"]
console.log(pages.next().value); // ["Bottle"]
console.log(pages.next().done); // true
A “Next page” button can simply call pages.next().
5. Combine two lists into pairs (zip)
function* zip(first, second) {
const a = first[Symbol.iterator]();
const b = second[Symbol.iterator]();
while (true) {
const x = a.next();
const y = b.next();
if (x.done || y.done) return; // stop with the shorter one
yield [x.value, y.value];
}
}
const names = ["Riya", "Karan", "Aman"];
const scores = [90, 75];
console.log([...zip(names, scores)]); // [["Riya", 90], ["Karan", 75]]
6. Process a huge list in small steps
function* primes() {
let n = 2;
while (true) {
let isPrime = true;
for (let d = 2; d * d <= n; d++) {
if (n % d === 0) {
isPrime = false;
break;
}
}
if (isPrime) yield n;
n++;
}
}
console.log([...take(primes(), 8)]); // [2, 3, 5, 7, 11, 13, 17, 19]
You never ask for “all primes”. You ask only for as many as you need. (take is the generator from the lazy tools section above.)
Bonus: how async/await relates to generators
yield pauses a function. await pauses a function too. This is not a coincidence: async/await was designed with the same idea. Here is a tiny helper that runs a generator and treats every yield like an await on a Promise:
function run(generatorFunction) {
const generator = generatorFunction();
return new Promise((resolve, reject) => {
function step(method, argument) {
let result;
try {
result = generator[method](argument); // next(value) or throw(error)
} catch (error) {
return reject(error);
}
if (result.done) return resolve(result.value);
Promise.resolve(result.value).then(
(value) => step("next", value), // send the resolved value back in
(error) => step("throw", error) // send a rejection in as an error
);
}
step("next");
});
}
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
run(function* () {
const user = yield wait(100, { name: "Riya" }); // like: await wait(...)
const posts = yield wait(100, ["post 1", "post 2"]);
try {
yield Promise.reject(new Error("server down"));
} catch (error) {
console.log("Caught:", error.message); // "Caught: server down"
}
return user.name + " has " + posts.length + " posts";
}).then(console.log); // "Riya has 2 posts"
The helper uses next(value) to send results into the paused generator, and throw(error) to send failures in. That is exactly how await feels: the code pauses, then continues with the Promise result, and try/catch works around it. You do not need this helper in real code, because async/await does it for you. It is a great way to understand what await really is.
Preview: async generators and for await...of
If the values arrive over time (from a server, for example), use an async function*. It can await inside, and yield values. You read it with for await...of (the Symbol.asyncIterator you saw in the Symbols lesson):
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* loadPages() {
for (let page = 1; page <= 3; page++) {
await wait(300); // pretend this is a network call
yield { page, items: [page * 10, page * 10 + 1] };
}
}
(async () => {
for await (const result of loadPages()) {
console.log("Loaded page", result.page, result.items);
}
console.log("All pages loaded");
})();
// "Loaded page 1 [10, 11]"
// "Loaded page 2 [20, 21]"
// "Loaded page 3 [30, 31]"
// "All pages loaded"
The loop waits for each page, and you can break early to stop loading more. With a real API, the await would be a fetch call (see the async/await lesson), one page per request. This is a common pattern for paginated APIs and streams. Inside a module you can also use for await at the top level.
Common mistakes
- Forgetting the star (
function greet() { yield 1; }).yieldis then a syntax error. - Expecting the call to run the code.
const gen = steps();runs nothing. Callgen.next(), or loop over it. - Reusing a finished generator. It stays finished. Call the generator function again for a fresh one.
- Using
yieldinside a callback such asarray.forEach(...).yieldworks only directly in the generator function itself, not in a nested function. Use afor...ofloop instead. - Writing
yield gen()instead ofyield* gen(). The first gives the generator object; the second gives its values. - Passing a value to the first
next()and expecting it to arrive. The firstnext()value is ignored. - Spreading an infinite generator (
[...naturals()]). The page freezes. Usebreakortake. - Using an arrow function for a generator. It is not allowed.
- Calling
newon a generator function. It is aTypeError. - Confusing
returnandyield.returnends the generator.for...ofand spread ignore the returned value. - Forgetting that every call to the generator function is a new, independent generator. Store it in a variable if you want to continue the same one.
- Forgetting
finallywhen a generator holds a resource. Without it, nothing closes the resource when the loop stops early. - Forgetting to handle a rejection in an async generator loop. Wrap
for awaitintry/catch.
Practice
- Write
function* threeNumbers()that yields 1, 2 and 3. Call it, print the generator, then callnext()four times and print each result. - Add
console.loglines between the yields. Predict the order of the logs before you run it. - Loop over a generator with
for...of, then spread it, then destructure the first two values. - Prove that a generator is used up: spread it twice and compare.
- Create two generators from the same function, and show that they keep separate positions.
- Write an infinite
naturals()generator. Print the first five values withnext(), then withfor...ofandbreak. - Write
take,mapandfiltergenerators. Get the first 4 even squares fromnaturals(). - Write
range(start, end, step)and use it to print the even numbers from 2 to 20. - Write
chunk(iterable, size)and split a list of 10 items into groups of 4. - Write
chat()with twoyieldquestions, and answer it withnext("..."). Write down what happens with the value in the firstnext(). - Write a
runningTotalgenerator that receives numbers withnext(number)and yields the total so far. - Write a generator with
try...finallyand stop the loop early withbreak. Check that thefinallymessage appears. Then callgen.return("x")by hand and check again. - Write a generator that catches an error sent with
gen.throw(...)and keeps running. - Use
yield*to join two arrays and a string into one sequence. - Write
flatten(items)with recursion andyield*. Test it on[1, [2, [3, [4]]]]. - Write
walk(node)for a small folder tree and print the names with indentation. - Make your own class iterable with
*[Symbol.iterator](). Loop over it, spread it and destructure it. - Write
cycle(items)andtrafficLight(). Print 7 values from each. - Write
paginate(items, size)and connect it to a “Next page” button. - Challenge: write
zip(a, b)andunzipthat goes back from pairs to two arrays. - Challenge: write a
primes()generator and print the first 15 primes. - Challenge: write a generator-based wizard with three steps that waits for
next(answer)and finally returns a summary of the answers. - Challenge: write the
run(generatorFunction)helper from memory and use it with two fake delayed Promises. - Challenge: write an
async function*that “loads” four pages with a delay, and usefor await...ofwithbreakafter the second page.
Recap
- A generator function is written with
function*. Calling it runs no code and returns a generator object. yield valuepauses the function and givesvalueout.gen.next()resumes it until the nextyield, and returns{ value, done }. Areturnends it withdone: true.- A generator remembers its local variables between pauses. It is lazy: it runs only when asked, so an endless
while (true)loop is safe. - A generator object is both an iterator and an iterable, so it works with
for...of, spread, destructuring,Array.from,Setand more. It is used up after one pass, but each call to the generator function creates a new, independent generator. next(value)sends a value into the pausedyield(the firstnext()’s value is ignored).return(value)ends it early,throw(error)raises an error at the pausedyield. Atry...finallyinside gives automatic cleanup when a loop stops early.yield*delegates to another iterable or generator (and returns its return value). With recursion it flattens nested data and walks trees in a few lines.*[Symbol.iterator]() { ... }is the easiest way to make a class or object iterable.- Use generators for lazy and infinite sequences, IDs, pagination, state machines, tree walking, and small tools like
take,map,filter,range,chunkandzip. yieldandawaitare related ideas. Async generators (async function*withfor await...of) handle values that arrive over time.- Generators cannot be arrow functions, cannot use
new, andyieldworks only directly inside the generator function, not in nested callbacks. - You have now finished the core of object-oriented and advanced JavaScript:
this, prototypes, classes, modules, descriptors, Proxy, iterators and generators. Next you will look at how JavaScript manages memory.
If you want to revisit the basics, read the iterators lesson, the closures lesson, the Promises lesson and the async/await lesson.
Frequently asked questions
What is a generator in JavaScript?
A generator is a special function, written with function*, that can pause at yield and resume later from the same place with all its variables intact. Calling it returns a generator object, which is an iterator you can step through with next() or loop over with for…of.
What does yield do?
yield pauses the generator and gives a value to the code that called next(). When next() is called again, the generator resumes right after the yield. If you pass a value to next(value), that value becomes the result of the yield expression.
Why does nothing happen when I call my generator function?
Calling a generator function only creates a generator object. None of the function’s code runs until you call next() or start a loop over it.
What is the difference between yield and yield*?
yield gives out one value. yield* delegates to another iterable or generator and gives out all of its values, one at a time. Writing yield other() without the star would give out the generator object itself instead of its values.
What is the difference between a generator and an iterator?
An iterator is any object with a next() method that follows the iterator protocol. A generator is a quick way to create one: you write a function with yield and JavaScript builds the iterator, including the state handling, for you.
Can a generator run forever?
Yes, because it only runs when asked. An infinite generator, such as one with while (true), is fine as long as you take a limited number of values, for example with break or a take helper. Spreading it into an array would never finish.
Do I still need generators now that we have async/await?
For everyday asynchronous code, async/await is usually all you need. Generators are still great for lazy and infinite sequences, custom iterables, tree walking and state machines, and async generators are useful for streams and paginated data.
See also: Iterators, Symbols, Async and Await, JavaScript Cheat Sheet