Iterator
Provides a way to sequentially access elements of a collection without exposing its underlying representation.
errorWhat Problem Does the Iterator Pattern Solve?
Different collection types—arrays, linked lists, trees, graphs—each have their own traversal logic. Client code that directly traverses a collection becomes tightly coupled to its internal structure, making it impossible to swap collection types or support multiple simultaneous traversals without breaking clients.
check_circleHow the Iterator Pattern Works
Extract the traversal logic into an Iterator object that implements a common interface with methods like hasNext and next. The collection provides a factory method that creates the appropriate iterator for its structure. Client code traverses any collection uniformly through the iterator interface, ignorant of the underlying data structure.
Iterator Pattern Architecture
Rendering diagram...
Implementation by Language
Iterator Pattern in the Real World
“Think of a TV remote control. Whether your playlist is on a Blu-ray disc, a streaming service, or a USB drive, you use the same next and previous buttons to cycle through content. The remote (iterator interface) abstracts away the completely different internal mechanisms each media source uses to retrieve the next item.”
Frequently Asked Questions
helpWhy use the Iterator pattern when most languages have built-in loops?
Built-in loops (for, forEach) work for simple collections. Iterator is needed when traversal logic is complex (tree traversal, paginated API results, lazy evaluation), when you want to support multiple simultaneous traversals, or when you need to hide the collection's internal structure.
helpHow does Iterator relate to JavaScript generators?
JavaScript generators (function*) are a built-in Iterator implementation. They yield values lazily and maintain internal state between calls. Generators implement the Iterator protocol (Symbol.iterator), making them usable with for...of loops and spread syntax.