Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
JS

JavaScript

The language of the web, on the client, the server and the edge.

Paradigm
Multi-paradigm, prototype-based, functional
Typing
Dynamic, weak (TypeScript adds static types)
Memory
Garbage collected
Runs
V8 / SpiderMonkey / JSC engines (JIT)
Concurrency
Single-threaded event loop, workers
Behavioral pattern

Iterator

Intent

Traverses elements of a collection without exposing its underlying representation.

Problem

Clients need to walk a tree depth-first, breadth-first or randomly without knowing how it's stored.

Solution

Extract traversal into iterator objects; most languages now build this in (foreach, for…of, range, generators).

Real-world analogy

Think of it like this

Touring a city: with a paper map, a guide or an app. Same sights, different ways to walk through them.

Structure

association / extends implements / depends on
«interface» Iterator + getNext()+ hasMore(): bool 1 «interface» IterableCollection + createIterator(): Iterator 3 ConcreteIterator - collection- iterationState+ getNext()+ hasMore(): bool 2 ConcreteCollection + createIterator(): Iterator 4 Client 5

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Iterator — Iterator declares traversal operations.
  2. 2ConcreteIterator — Concrete Iterators implement one traversal algorithm and track their own position.
  3. 3IterableCollection — Iterable Collection declares a method that returns a compatible iterator.
  4. 4ConcreteCollection — Concrete Collections return a new iterator each time a client asks.
  5. 5Client — Client works through the interfaces, so collections and iterators stay interchangeable.

Code example

A JavaScript code sample for Iterator is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Iterator when hiding a complex data structure.

Use Iterator when reducing duplicated traversal code.

Pros and cons

Pros

  • Single Responsibility and Open–Closed
  • Parallel iteration over the same collection

Cons

  • Overkill for simple collections

Relations with other patterns

Check yourself

Check yourself

Clients loop over a custom tree depth-first or breadth-first without knowing how it is stored.

Saved in this browser only. Part of Behavioral patterns (0/11).