Core Language

Iterators & Generators

Iterators give you a standard protocol to traverse any data structure. Generator functions let you write iterators with plain-looking code usingfunction* andyield — including infinite sequences, lazy evaluation, and async data streams.

What are generators in JavaScript?

A generator is a function declared with function* that can pause with yield and resume later, producing a sequence of values on demand. Calling it returns an iterator that you can loop over with for…of. Generators are good for lazy sequences, such as infinite IDs or paging through data, without building whole arrays in memory.

function* range(start, end) {
  for (let i = start; i < end; i++) yield i;
}
for (const n of range(0, 3)) console.log(n);   // 0 1 2
[...range(1, 4)];                             // [1, 2, 3]

const it = range(0, 2);
it.next();   // { value: 0, done: false }

Iterator Protocol

An object is an iterator if it has a next() method that returns { value, done }.

const iter = {
next() {
return { value: 42, done: false };
}
}
iter.next(); // { value: 42, done: false }

Iterable Protocol

An object is iterable if it has a [Symbol.iterator]() method returning an iterator. This unlocks for…of, spread, and destructuring.

  • Array, String, Map, Set, arguments — all built-in iterables
  • for…of calls [Symbol.iterator]() automatically
  • Spread [...iterable] consumes the iterator
  • Destructuring [a, b] = iterable also uses the protocol

Generator Functions

Lazy evaluation

Values are produced on demand — not all at once. Perfect for large/infinite sequences.

Stateful pausing

function* remembers local variables between yields. No external state machine needed.

Two-way data flow

Pass values back in via next(value) — the yield expression evaluates to that value.

function* count() {
let n = 0;
while (true) {
const reset = yield n++;
if (reset) n = 0;
}
}
// Infinite counter with optional reset

Async Generators

async function* combines generators with Promises. Each yield can await async operations, and consumers use for await…of. This is perfect for paginated APIs, database cursors, reading streams, and WebSocket message processing.

async function* streamData(url) {
let page = 1;
while (true) {
const data = await fetch(`${url}?page=${page++}`).then(r => r.json());
if (!data.items.length) return;
yield data.items;
}
}
// for await (const items of streamData('/api')) { … }

Common Pitfalls

Iterating a generator twice — generators are single-use
Store results in an array or make the containing object iterable (not the generator itself)
Spreading an infinite generator: [...infiniteGen()]
Take only what you need using take() utility or break out of for…of loops
Forgetting that return value has done: true — not consumed by for…of
If you need the return value, use next() manually instead of for…of
Arrow functions cannot be generators (no arrow function* syntax)
Use regular function* declarations or function* expressions for generators

Interactive Examples

Code Editor

<pre id="out"></pre>

Preview

Iterators and generators — step by step

1 / 4
1

The iterator protocol

An iterator is any object with a next() method that returns { value, done }. When done is true, iteration is complete. The iterable protocol requires a [Symbol.iterator]() method that returns an iterator. This is what for...of, spread, and destructuring use under the hood — they call [Symbol.iterator]() to get the iterator, then repeatedly call next().

1 of 4
🔍Generators enable lazy evaluation
Unlike arrays (which hold all values in memory), generators produce values one at a time on demand. A generator for all natural numbers never runs out of memory because it only computes the next value when asked. This makes generators ideal for large data sets, infinite sequences, and pipeline transformations.

🎯 Quick Check

What does calling a generator function (e.g. gen()) immediately return?

Iterators and Generators: summary

Key points

  • An iterator is any object with a next() method that returns { value, done }.
  • An object is iterable if it has a [Symbol.iterator]() method; arrays, strings, Maps and Sets all do.
  • async function* and for await…of handle streams of asynchronous data.

Frequently asked questions

›What is the difference between an iterator and an iterable?

An iterable can produce an iterator (via Symbol.iterator); the iterator is the object you actually call next() on.