Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 156 Β· Built-in Tools

Iterators and Generators

Learn the iteration protocol behind for...of and spread, write generator functions with yield, build lazy and infinite sequences, and loop over async data.

You have used for...of on arrays, strings, Maps and Sets, and spread them with .... But how does for...of know how to walk through such different things? And why can't you use it on a plain object? The answer is a small agreement called the iteration protocol. Any object that follows it works with for...of, spread, destructuring, Array.from() and more.

In this lesson you will learn that protocol, make your own objects iterable, and then meet generators β€” special functions that can pause and resume, which make writing iterators almost effortless. You will finish with lazy sequences and async iteration, which lets you loop over data that arrives over time.

The iteration protocol

The protocol has two parts:

  1. An object is iterable if it has a method under the key Symbol.iterator that returns an iterator.
  2. An iterator is an object with a next() method. Each call returns a result object { value, done }. When there is nothing left, it returns { value: undefined, done: true }.

You can drive an iterator by hand to see exactly what for...of does behind the scenes:

JS Driving an iterator by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Symbol.iterator is one of the "well-known symbols" from the BigInt and Symbol lesson. Plain objects don't have it, which is why you loop over them with Object.entries() (see Working with Objects) instead.

Making your own iterable

Any object can become iterable by adding a [Symbol.iterator]() method. Here is a range of numbers that works with every iteration feature:

JS A custom iterable range

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each call to [Symbol.iterator]() returns a fresh iterator with its own current, so you can loop over range as many times as you like.

That works, but the hand-written next() with its result objects is clumsy. Generators fix that.

Generator functions

A generator function is written with function* (note the star). Calling it does not run its body. Instead, it returns a generator object, which is both an iterator and an iterable. Each time you call next(), the body runs until the next yield, hands that value out, and pauses right there β€” local variables and all β€” until the next next().

JS Pausing at yield

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The range from before shrinks to a few lines:

JavaScript
function* range(from, to, step = 1) {
  for (let n = from; n <= to; n += step) yield n;
}

[...range(0, 20, 5)]; // [0, 5, 10, 15, 20]

Generators also work as methods. A class can make its instances iterable with *[Symbol.iterator]() { … }:

JavaScript
class Playlist {
  #songs = [];
  add(song) { this.#songs.push(song); return this; }
  *[Symbol.iterator]() {
    for (const song of this.#songs) yield song.title;
  }
}

const mix = new Playlist().add({ title: "Low Tide" }).add({ title: "Paper Moon" });
[...mix]; // ["Low Tide", "Paper Moon"]

Delegating with yield*

yield* hands control to another iterable and yields each of its values in turn. It is perfect for recursive structures like trees:

JavaScript
function* walk(node) {
  yield node.name;
  for (const child of node.children ?? []) yield* walk(child);
}

const tree = { name: "src", children: [{ name: "app.js" }, { name: "lib", children: [{ name: "math.js" }] }] };
[...walk(tree)]; // ["src", "app.js", "lib", "math.js"]

Compare this with the recursion lesson: the generator version produces values one at a time instead of building a whole array.

Lazy and infinite sequences

Generators are lazy: they compute a value only when someone asks for it. That means a generator can describe an infinite sequence safely, as long as the consumer stops at some point.

JS Infinite sequences, taken lazily

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Calling [...naturals()] would run forever, so always limit an infinite generator before spreading it. When a for...of loop exits early (with break or return), it calls the iterator's return() method, which finishes the generator and runs any finally block inside it β€” so cleanup code still happens.

Built-in iterator helpers

Modern JavaScript adds those helpers directly to iterators: .map(), .filter(), .take(), .drop(), .flatMap(), .reduce(), .toArray(), .forEach(), .some(), .every() and .find(). They work on any built-in iterator, including generators.

JavaScript
naturals().filter((n) => n % 2 === 0).map((n) => n * n).take(5).toArray();
// [4, 16, 36, 64, 100]

Browser support: iterator helpers reached all major browsers between 2024 and early 2025 (Safari 18.4 was last). Check with typeof Iterator !== "undefined" && "take" in Iterator.prototype, or use your own small generator helpers like the ones above for older browsers.

Two-way communication

next() can also send a value into a generator: the argument becomes the result of the paused yield expression. This is how generators were once used to write async code (before async/await), and it is still handy for small state machines.

JavaScript
function* runningAverage() {
  let total = 0, count = 0, average;
  while (true) {
    const value = yield average; // receive a number, hand back the average
    total += value;
    count++;
    average = total / count;
  }
}

const avg = runningAverage();
avg.next();              // start it: runs to the first yield
avg.next(10).value;      // 10
avg.next(20).value;      // 15
avg.next(60).value;      // 30

Async iteration

Some data arrives over time: pages of results from an API, chunks of a file, messages from a server. For that there is an async version of everything:

  • An async generator (async function*) can await inside and yield values.
  • for await...of loops over an async iterable, waiting for each value.
  • The protocol uses Symbol.asyncIterator, and next() returns a promise of { value, done }.

The example fakes a paginated API with a timer, since the sandbox has no server. It uses module="true" so that await can be used at the top level.

JS Async generators and for await...of

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The caller simply loops over users; the generator decides when to load the next page. Breaking out of the loop stops the generator, so no extra requests are made. for await also works on readable streams in modern browsers and Node.js, and Array.fromAsync() collects an async iterable into an array. To learn more about await itself, see async and await.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What makes an object usable in a for...of loop?

    for...of calls [Symbol.iterator]() and then next() repeatedly. That method is the whole protocol.
  2. 2. What happens when you call a generator function such as countdown()?

    Calling a generator function only creates the generator. Each next() runs the body up to the next yield.
  3. 3. Why is [...naturals()] a problem when naturals yields forever?

    Spread keeps calling next() until done is true, which never happens. Limit infinite sequences with something like take() first.
  4. 4. What does yield* do?

    yield* delegates to another iterable or generator and passes along each value it produces.
  5. 5. Which loop consumes an async generator?

    for await...of awaits each next() promise and gives you the values in order.

Summary

  • The iteration protocol: [Symbol.iterator]() returns an iterator whose next() returns { value, done }.
  • for...of, spread, destructuring and Array.from() all use this protocol, so any iterable works with them.
  • Generator functions (function*) return generator objects that pause at each yield and resume on next().
  • yield* delegates to another iterable β€” ideal for trees and nested data.
  • Generators are lazy, so infinite sequences are fine if you limit them; iterator helpers like .take() are now built in.
  • async function* and for await...of iterate over data that arrives over time.

Next: Proxy and Reflect β€” intercept and customize what happens when code touches an object.