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

«create»fetches pages«interface»Iterable<Order>+ [Symbol.iterator](): Iterator«interface»Iterator<Order>+ next(): IteratorResultAllOrders- api: OrdersApi+ [Symbol.iterator]()OrderIterator- buffer: Order[]- cursor?: string+ next()OrdersApi+ fetchPage(cursor): Page

Iterator pattern class diagram

  1. Interface Iterable<Order> with + [Symbol.iterator](): Iterator.
  2. Interface Iterator<Order> with + next(): IteratorResult.
  3. Class AllOrders with + [Symbol.iterator]().
  4. Class OrderIterator with + next().
  5. Class OrdersApi with + fetchPage(cursor): Page.
  6. AllOrders implements Iterable<Order>.
  7. OrderIterator implements Iterator<Order>.
  8. AllOrders creates OrderIterator.
  9. OrderIterator fetches pages OrdersApi.

Sequence diagram

for…of loopOrderIteratorOrdersApiopt[buffer empty]1. next()2. fetchPage(cursor)3. 3 orders + nextCursor4. { value: A-100, done: false }5. next()6. { value: A-101 } from buffer7. next() … after the last page8. { done: true }

Iterator pattern sequence diagram

  1. for…of loop → OrderIterator: next().
  2. OrderIterator → OrdersApi: fetchPage(cursor).
  3. OrderIterator receives "3 orders + nextCursor" back from OrdersApi.
  4. for…of loop receives "{ value: A-100, done: false }" back from OrderIterator.
  5. for…of loop → OrderIterator: next().
  6. for…of loop receives "{ value: A-101 } from buffer" back from OrderIterator.
  7. for…of loop → OrderIterator: next() … after the last page.
  8. 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.ts
// 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…of directly.
  • 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.