foundation

Iterator

Expose sequential access to a collection without revealing storage details, supporting streams, generators, and traversal APIs.

Iterator exposes sequential access to a collection without revealing internal storage—arrays, linked structures, database cursors, async streams, generators. Language features like `for...of`, async iterators, and lazy sequences are everyday iterators. Design choices include mutability during traversal and fail-fast versus snapshot semantics.

On interviews: implement or explain a custom iterator. Contrast internal iterators (callbacks) with external iterators (pull model).

Common pitfalls: modifying collections during iteration; unbounded async iterators without cancellation; exposing implementation details through rich iterator types.

The trade-off is flexibility versus complexity—know when the simpler path is enough.

Checklist:

  • Iteration contract documented (sync/async).
  • Concurrent modification handled safely.
  • Lazy iteration for large datasets.
  • Consumers depend on iterator protocol, not storage.