Lesson 5, by Codesarray, , 9 min read

JavaScript iterators and generators: yield, for...of, lazy pipelines

Learn JavaScript iterators and generators: the next() protocol behind for...of, Symbol.iterator to make your own objects loopable, function* and yield, and lazy pipelines over an infinite sequence with the ES2025 iterator helpers.

JavaScript iterators and generators run every for...of loop you have ever written, and they hide one of the language's best surprises: call a generator function and none of its body runs. Not the first line, nothing. The body only moves when you ask for a value, and then it runs exactly as far as the first yield and freezes mid-function, locals intact, waiting. This page explains the protocol behind that trick: next() and { value, done }, Symbol.iterator to make your own objects loopable, function* and yield, and lazy pipelines that sail through infinite data with the ES2025 iterator helpers. Everything here ran on Node 24.

The iteration protocol: next() and { value, done }

Think of a book with a bookmark. The book is the data; the bookmark remembers where you are. In JavaScript the bookmark is called an iterator, and it has one job: a method named next(). Every call reads one item, moves the bookmark forward, and answers with the same little report: value, the item it found, and done, a boolean that says whether the bookmark is past the end. for...of is just a polite loop that calls next() again and again until done says true.

You can catch it in the act. Ask an array for its own iterator and drive it by hand:

const nums = [10, 20, 30];

const it = nums[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

const it2 = nums[Symbol.iterator]();
let result = it2.next();
while (!result.done) {
  console.log(result.value);
  result = it2.next();
}
{ value: 10, done: false }
{ value: 20, done: false }
{ value: 30, done: false }
{ value: undefined, done: true }
10
20
30

Three items, three reports with done: false, and then the fourth call falls off the end: value: undefined, done: true. The while loop at the bottom is for...of played in slow motion — grab a fresh iterator, keep reading reports until done is true — and it prints the same 10 20 30 with no for...of in sight.

Symbol.iterator: make any object loopable

Who gets to hand out bookmarks? Anything with a method stored at the key Symbol.iterator. That is called an iterable. Arrays, strings, Map and Set all have it; a plain object does not, which is why looping over one throws "is not iterable".

Here is the beautiful part. A music player does not care how your playlist stores its songs; it only ever asks one thing: next song, please. Write that one method on your object and every loop in the language can play it:

const playlist = {
  name: "Road Trip",
  songs: ["Dream On", "Yellow", "Africa"],

  [Symbol.iterator]() {
    const songs = this.songs;
    let i = 0;
    return {
      next() {
        if (i < songs.length) {
          return { value: songs[i++], done: false };
        }
        return { value: undefined, done: true };
      },
    };
  },
};

for (const song of playlist) {
  console.log(song);
}

console.log([...playlist]);
const [first] = playlist;
console.log(first);
Dream On
Yellow
Africa
[ 'Dream On', 'Yellow', 'Africa' ]
Dream On

The method returns an iterator: an object with a next() that reports the current song and moves a counter, or reports done: true when the songs run out. That one method unlocks everything at once — for...of, spread, and destructuring all work on your own object, because they all speak the same protocol.

Generators: a function with a pause button

That hand-written iterator was bookkeeping: a counter, an if, two report objects, for three songs. JavaScript has a machine that writes iterators for you — the generator. Put a star after the function keyword and use a new word inside: yield.

A normal function is a movie with no remote: it plays start to finish, every time. A generator plays to the next yield, hands you a value, and pauses — locals, position, everything kept warm — until the next next() resumes it exactly where it stopped.

function* countdown() {
  console.log("Ready...");
  yield 3;
  yield 2;
  yield 1;
  console.log("Lift off!");
}

const g = countdown();
console.log(g.next());
console.log(g.next());
console.log(g.next());
console.log(g.next());

const playlist = {
  songs: ["Dream On", "Yellow", "Africa"],
  *[Symbol.iterator]() {
    yield* this.songs;
  },
};

console.log([...playlist]);
Ready...
{ value: 3, done: false }
{ value: 2, done: false }
{ value: 1, done: false }
Lift off!
{ value: undefined, done: true }
[ 'Dream On', 'Yellow', 'Africa' ]

Look closely at the order. const g = countdown() prints nothing — calling a generator runs none of the body; it only builds the iterator. The first g.next() runs the body for real: Ready... prints, the function reaches yield 3, and freezes. Each later call resumes the freeze, and the fourth one runs past the last yield to the end, through Lift off!, and reports done: true.

The playlist comes back too, rewritten: the whole fourteen-line hand-written iterator is now one line, yield* this.songs. yield* means "yield everything from that iterable, one by one". Same protocol underneath; the generator just writes it for you.

Lazy pipelines over an infinite generator

Now the superpower. An array is a warehouse: every value built up front and stored in memory, whether anyone reads it or not. An iterator is a conveyor belt: nothing exists until someone asks, and then it makes exactly one item. Which means you can put infinity on the belt — a while (true) loop that yields forever is a perfectly good generator, as long as you never ask it for everything.

Since ES2025, iterators carry their own helpers — map, filter, take, drop, toArray — straight on the iterator. They look like array methods, but they are belt sections: each processes one item at a time, on demand.

function* naturals() {
  let n = 1;
  while (true) {
    yield n++;
  }
}

const evenSquares = naturals()
  .map((n) => n * n)
  .filter((n) => n % 2 === 0)
  .take(4)
  .toArray();
console.log(evenSquares);

console.log(naturals().drop(99).take(3).toArray());

function* chain(...sources) {
  for (const source of sources) {
    yield* source;
  }
}

console.log(chain([1, 2], new Set([3]), "ab").toArray());
[ 4, 16, 36, 64 ]
[ 100, 101, 102 ]
[ 1, 2, 3, 'a', 'b' ]

The first four even squares, from an infinite sequence, and it finishes instantly — take(4) is the guard rail that stops the belt asking after four items pass, so only a handful of numbers ever existed. drop(99).take(3) skips ninety-nine and grabs three, no loop in sight. ES2026 adds Iterator.concat to glue belts end to end; it has not landed in Node yet, and the four-line chain generator above does the same job today: an array, a Set and a string, three different containers on one smooth belt.

One warning: never spread an infinite iterator. Spread is a warehouse move — it asks for everything, forever.

One iterator, one trip

One last catch, and it bites almost everyone:

const nums = [10, 20, 30];
const it = nums.values();
console.log([...it]);
console.log([...it]);
[ 10, 20, 30 ]
[]

The second spread prints an empty array. An iterator is one bookmark, for one trip: the first spread drove it all the way to done, and a finished iterator stays finished. The array itself is re-iterable — ask it again and Symbol.iterator hands you a fresh bookmark — but the old bookmark never rewinds.

What you learned

  • An iterator is a bookmark: next() returns { value, done }, and for...of just calls it until done is true.
  • An iterable is anything with a method at the key Symbol.iterator; write that one method and for...of, spread and destructuring all work on your object.
  • function* builds the iterator for you: yield pauses with all locals kept, next() resumes, and calling the generator runs none of the body.
  • yield* delegates to another iterable — a hand-written iterator often collapses to one line.
  • Iterators are lazy: an infinite generator is fine, and the ES2025 helpers map, filter, take, drop and toArray process one item at a time, with take as the guard rail.
  • An iterator is one bookmark for one trip: spread it twice and the second spread gets [].

Common questions

Why does calling my generator do nothing? That is the design. Calling a generator function builds and returns the iterator; the body waits. The first next() runs it to the first yield and pauses there. If you want eager code plus lazy values, put the eager part in a normal function that returns the generator's iterator.

What is the difference between an iterable and an iterator? An iterable is something you can loop over: it has a [Symbol.iterator]() method that hands out iterators. An iterator is the bookmark itself: it has next(). Generators blur the line by being both, which is why for...of works directly on a generator object.

When should I use a generator instead of an array? When the values are expensive, endless, or read at most once: paging through an API, walking a tree, streaming lines from a file, or any sequence where you might stop early. If you need the values more than once, or need their length and random access, build the array.

Do the iterator helpers work on arrays? Not directly — map on an array is the eager array method. Get the array's iterator first: nums.values().map(...).take(2) stays lazy. On any iterator (including every generator object), the ES2025 helpers map, filter, take, drop and toArray are available in Node 24.

Why does spreading my iterator a second time give an empty array? The first spread consumed it: spread calls next() until done is true, and a finished iterator never rewinds. Spread the iterable (the array) instead of a saved iterator, or ask for a fresh iterator each time.

Next lesson: promises and async/await — how JavaScript waits for slow things without freezing, and how one picture of the event loop makes it all click.

This article goes with the video JavaScript Iterators and Generators: yield, for...of, lazy pipelines. Watch it on YouTube.