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 }.
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.
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.
Common Pitfalls
Interactive Examples
Code Editor
<pre id="out"></pre>Preview
Iterators and generators — step by step
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().
🎯 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*andfor await…ofhandle 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.