Iterator
Walk through the items of a collection one at a time without exposing how the collection is stored, whether it's an array, a tree or a paginated API.
Description
An iterator keeps track of where you are in a traversal and gives you the next item on request. The collection, the aggregate, hands out iterators but hides its internals: pages and cursors, tree nodes, database result sets.
JavaScript builds the pattern into the language. Anything with a [Symbol.iterator]() method works with for…of, spread and destructuring, and generator functions (function*) are the shortest way to write one. The example writes the iterator class out in full to show the moving parts, and fetches API pages lazily as the loop needs them.
Class diagram
Iterator pattern class diagram
- Interface Iterable<Order> with + [Symbol.iterator](): Iterator.
- Interface Iterator<Order> with + next(): IteratorResult.
- Class AllOrders with + [Symbol.iterator]().
- Class OrderIterator with + next().
- Class OrdersApi with + fetchPage(cursor): Page.
- AllOrders implements Iterable<Order>.
- OrderIterator implements Iterator<Order>.
- AllOrders creates OrderIterator.
- OrderIterator fetches pages OrdersApi.
Sequence diagram
Iterator pattern sequence diagram
- for…of loop → OrderIterator: next().
- OrderIterator → OrdersApi: fetchPage(cursor).
- OrderIterator receives "3 orders + nextCursor" back from OrdersApi.
- for…of loop receives "{ value: A-100, done: false }" back from OrderIterator.
- for…of loop → OrderIterator: next().
- for…of loop receives "{ value: A-101 } from buffer" back from OrderIterator.
- for…of loop → OrderIterator: next() … after the last page.
- for…of loop receives "{ done: true }" back from OrderIterator.
TypeScript example
A for…of loop over every order in a paginated API. The iterator fetches the next page only when its buffer runs out; the loop never sees pages or cursors.
// Iterator: walk every order across a paginated API with a plain for…of loop,
// without callers knowing about pages or cursors.
interface Order {
id: string;
total: number;
}
interface Page {
items: Order[];
nextCursor?: string;
}
// The source: a paginated API (faked here)
class OrdersApi {
requests = 0;
private readonly all: Order[] = Array.from({ length: 7 }, (_, i) => ({ id: `A-${100 + i}`, total: 10 * (i + 1) }));
fetchPage(cursor = "0", size = 3): Page {
this.requests += 1;
const start = Number(cursor);
const items = this.all.slice(start, start + size);
const next = start + size < this.all.length ? String(start + size) : undefined;
return { items, nextCursor: next };
}
}
// Concrete iterator: knows the traversal state; fetches pages lazily
class OrderIterator implements Iterator<Order> {
private readonly api: OrdersApi;
private buffer: Order[] = [];
private cursor: string | undefined = "0";
constructor(api: OrdersApi) {
this.api = api;
}
next(): IteratorResult<Order> {
if (this.buffer.length === 0 && this.cursor !== undefined) {
const page = this.api.fetchPage(this.cursor);
this.buffer = page.items;
this.cursor = page.nextCursor;
}
const order = this.buffer.shift();
return order ? { value: order, done: false } : { value: undefined, done: true };
}
}
// Aggregate: hands out iterators (for…of calls [Symbol.iterator]())
class AllOrders implements Iterable<Order> {
private readonly api: OrdersApi;
constructor(api: OrdersApi) {
this.api = api;
}
[Symbol.iterator](): Iterator<Order> {
return new OrderIterator(this.api);
}
}
export function demo(): string[] {
const api = new OrdersApi();
let sum = 0;
let firstBig = "";
for (const order of new AllOrders(api)) {
sum += order.total;
if (!firstBig && order.total >= 40) {
firstBig = order.id;
}
}
return [`sum of all orders: ${sum}`, `first order of 40 or more: ${firstBig}`, `API pages fetched: ${api.requests}`];
}When to use it
Use it when
- Callers should loop over items without knowing how they're stored or fetched.
- Data arrives in pages, streams or chunks, and you want it to look like one simple sequence.
- You need several independent traversals of the same collection at once.
- Items should be produced lazily: computed or fetched only when the loop asks.
Avoid it when
- It's already an array. Use array methods and
for…ofdirectly. - Callers need random access or the total count up front. An iterator only goes forward.
Pitfalls
- Changing the collection while iterating over it, which skips or repeats items. Iterate over a snapshot or collect changes for afterwards.
- Expensive lazy iterators consumed twice by accident: spreading a paginated iterator twice calls the API twice.
- Forgetting cleanup when a loop exits early. Iterators holding connections or file handles should implement
return()(generators get it automatically). - Hiding network calls behind something that looks like a cheap in-memory loop.
Alternatives
Generator function
Choose it when you write a custom iterator in JavaScript or TypeScript: function* handles state and cleanup for you.
Async iterator
Choose it when each step awaits I/O: for await (const order of orders()) with an async function*.
Visitor
Choose it when you run operations over a structure of different node types rather than step through a sequence.
Composite
Choose it when the structure is a tree and you mainly compute over it recursively.