Iterator Design Pattern Explained

Iterator provides a way to sequentially access elements of a collection without exposing its internal structure.

Published November 13, 2026

The Iterator pattern gives a standard way to walk through the elements of a collection one at a time without exposing its internal structure.

The concept

An iterator offers next() (and a way to know when it is done). The collection can be an array, tree or database cursor; the loop code stays the same.

Most modern languages build it in: JavaScript's iterators and for…of, Python's __iter__, Java's Iterable.

Pull one at a time

it.next()
{ value: 1, done: false }
it.next()
{ value: 2, done: false }
it.next()
{ value: undefined, done: true }

Practical examples

Custom iterable

class Range {
  constructor(a, b) { this.a = a; this.b = b }
  *[Symbol.iterator]() { for (let i = this.a; i <= this.b; i++) yield i }
}
[...new Range(1, 3)] // [1, 2, 3]

Python

class Countdown:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0: raise StopIteration
        self.n -= 1; return self.n + 1

Lazy infinite sequence

function* ids() { let i = 0; while (true) yield i++ }

Common mistakes

  • Modifying a collection while iterating over it.
  • Assuming iterators can be reused after exhaustion.
  • Loading everything into an array when a lazy iterator would do.

Key takeaways

  • Uniform traversal.
  • Generators make iterators easy.
  • Iterators can be lazy.

FAQ

Iterator vs generator?

A generator is a function that produces an iterator using yield.

Can iterators be infinite?

Yes, consumers just stop when they have enough.

More General articles