Skip to content
Modern JavaScriptChapter 43 / 47Advanced4 min read

Iterators & Generators

Learn what JavaScript iterators and generators are, how the iteration protocol, function* and yield work, with examples of lazy sequences.

On this page

1. What are iterators and generators?

for...of, spread ... and destructuring all use the iteration protocol under the hood. Arrays, strings, Map and Set can be looped for this reason: they are all iterable.

2. Why do they matter?

Sometimes you do not want all the values at once, but one by one. For example, pages of a big list, or an infinite sequence of IDs. Filling everything into an array first wastes memory.

Everything in an arrayWith a generator
The whole list must be built firstA value is created only when asked for
A big list fills up memoryOnly one value at a time
An infinite sequence is not possibleAn infinite sequence is easy
A custom object does not work in for...ofSymbol.iterator makes it loopable

3. Where are they used?

Use caseExample
Custom data structuresMake your own LinkedList work with for...of
Lazy sequencesIDs, Fibonacci, or a range created on demand
PaginationFetch API pages one by one with for await...of
StreamsNode.js streams and ReadableStream are async iterable
LibrariesLibraries like Redux-Saga are built on generators

4. How do they work?

An iterator's next() returns an object each time: { value, done }. When done becomes true, the loop stops.

A generator function pauses at yield and continues from the same place on the next next() call.

Generator flow
The generator function is called
You get an iterator object, and no code has run yet
next() is called
The code runs up to the first yield and pauses
The value comes back, done is false
At the end the function finishes, done is true

5. Code example

An iterator by hand

js
const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        }
        return { value: undefined, done: true };
      },
    };
  },
};

for (const n of range) {
  console.log(n);
}

The same thing with a generator

js
function* rangeGen(from, to) {
  for (let i = from; i <= to; i++) {
    yield i;
  }
}

console.log([...rangeGen(1, 3)]);

function* idMaker() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const ids = idMaker();
console.log(ids.next().value);
console.log(ids.next().value);

Async generator

js
async function* fetchPages(url) {
  let page = 1;
  while (page <= 3) {
    const res = await fetch(`${url}?page=${page}`);
    yield await res.json();
    page++;
  }
}

for await (const data of fetchPages("/api/posts")) {
  console.log(data);
}

How does the code work?

ItemMeaning
[Symbol.iterator]()Makes the object iterable, and for...of calls it
next()Returns { value, done }
function*A generator function, it returns an iterator when called
yield iSend a value out and pause
while (true)An infinite loop is safe because it pauses at every yield
for await...ofAwaits values from an async generator one by one

Interview tip

"What is the difference between an iterable and an iterator?" An iterable is an object that has a Symbol.iterator method. An iterator is the object you get from that method, and it has next(). A generator object is both.

6. Common mistakes

Mistake: Calling a generator like a normal function

Why? Calling rangeGen(1, 3) does not run the code, it only gives you an iterator object.

Better: Pull out the values with for...of, spread or next().

Mistake: Spreading an infinite generator

Why? Spread tries to collect all the values, and with an infinite sequence the page hangs.

Better: Use next() or a loop with break for infinite generators.

Mistake: Looping the same iterator twice

Why? Once a generator object is finished, it does not give any more values.

Better: Call the generator function again for a new loop.

7. What to learn before and after

Final quick revision

PointDetail
IterableHas Symbol.iterator
IteratorHas next() that returns { value, done }
GeneratorA function* that pauses at yield
LazyA value is created only when asked for
Asyncasync function* and for await...of