Pattern 07/22 · Behavioral
Iterator
Traverse a collection without exposing how it is stored: array, map, tree, or pages of remote data. The outside only sees `next()` returning `{ value, done }`, and `for...of` runs on exactly that contract.
01 — It starts with code that is breaking
Problem
Your Nuxt app keeps a component tree shaped as { value, children? }. The folder-tree page needs to list it: function walk(nodes) { for (const n of nodes) { render(n); walk(n.children ?? []) } }. Done in five minutes, works fine.
Then you need "find the first node named Modal.vue". walk does not let you stop halfway — it visits everything. So you copy the whole loop and change it to if (found) return. Next up: "the first 5 nodes", "breadth-first traversal", "skip collapsed nodes", "traverse for serialization but do not descend into node_modules". Every request is another copy of the same loop, and each copy is wrong in its own way — one misses the last node, another loops forever if the tree has a cycle.
Then the collection stops being a pure tree: the first 200 nodes are in memory, the rest are fetched page by page. The loop now has to await while also remembering "which node am I on, which page, what cursor". The traversal logic and the data-fetching logic are tangled into one knot, and an API change breaks all six copies.
The silent enemy: outside code already knows too much. It knows children is an array, knows the field is called value, knows the root lives at state.nodes. The day you change children?: Node[] to children: Map<string, Node> — a purely internal change — you have to fix nine scattered places in the UI, each with its own flavor of indexing.
The only thing that truly varies is how to get from one element to the next. Chain of Responsibility asks "who handles this"; here the question is "which one comes next" — and that answer should live in one place, behind a small contract.
02 — The idea, before touching code
Solution
Separate "how to traverse" from "who is traversing". An Iterator is a small, stateful object with exactly one method: next() returning { value, done }. It remembers where it is by itself. The collection just hands out iterators, and nobody gets to know what it holds inside.
JavaScript already defines this contract, you do not have to invent one: an object with a Symbol.iterator() method is an iterable; what it returns (something with next()) is an iterator. for...of, spread [...x], Array.from, destructuring, yield*, new Map(pairs) all use just those two things. Which means the iterator you write today works in every piece of syntax the language has, no custom API needed.
Two properties that pay off. Stateful: ask the same collection for two iterators for two loops running side by side, and they do not step on each other. Lazy: values are only produced when the caller actually asks — exactly what pagination needs, because you do not want to fetch 10,000 rows just to show 20 and have the user hit ESC.
03 — Doing it for real, one code fragment per step
Step by step
Write the "expose all the internals" version first
This version is not wrong, it is just shaped like the data structure. Every time the structure changes, every copy has to change with it. That is what we are about to get rid of.
Notice that find cannot stop early: it has to call walk, and walk visits everything. What is missing is not an if condition, it is the ability to pause.
type Tree = { value: string, children?: Tree[] }
// Leaks structure: the caller has to know children is an array, and what field value is
function walk(nodes: Tree[], visit: (v: string) => void) {
for (const n of nodes) {
visit(n.value)
walk(n.children ?? [], visit)
}
}
// Want to stop early? Copy the whole loop, change one line.
function findFirst(nodes: Tree[], want: string): string | null {
for (const n of nodes) {
if (n.value === want) return n.value
const hit = findFirst(n.children ?? [], want)
if (hit) return hit
}
return null
}Two concepts: the iterable is where you ASK, the iterator IS the traversal
What trips people up is thinking the two are one thing. An iterable has no state: it just has Symbol.iterator() to ask for a fresh traversal. An iterator has state: it is the running cursor. Call Symbol.iterator() twice on the same array and you get two independent iterators — which is why two nested loops work.
An iterator is one-shot: once it reaches done: true it is finished, it does not reset itself. To traverse again, ask for a new iterator (i.e. for...of again, since for...of calls Symbol.iterator() for you).
interface Iterable<T> {
[Symbol.iterator](): Iterator<T> // ask for a traversal
}
interface Iterator<T> {
next(): IteratorResult<T> // { value, done: false } | { value, done: true }
return?(value?: T): IteratorResult<T> // early close: break/throw calls it
}
// Plain objects are NOT iterable: for...of {} throws.
// Object.keys/values/entries produce iterable arrays -> the official bridge.Generators: write a normal loop, get both an iterator and an iterable
function* is the cheapest way to get a spec-compliant iterator: you write recursion as usual, yield marks a pause point, and the engine saves all the state (stack position, local variables) for you. yield* delegates to another iterator — that is how recursion works without managing a stack yourself.
A generator object is both an iterator (it has next()) and an iterable (gen[Symbol.iterator]() returns itself). That is why it slots into for...of, spread, Array.from, and another generator's yield*.
function* walk(node: Tree): Generator<string> {
yield node.value // pause right here
for (const child of node.children ?? [])
yield* walk(child) // delegate to the subtree's traversal
}
for (const v of walk(root)) {
if (v === 'Modal.vue') break // stop early: the rest is never computed
}
;[...walk(root)] // spread also only takes what it needsHand-written iterator: the `stack` is its state
When the state is more complex than "an array index" — trees, graphs, several sources chained together, a remote cursor — you write next() yourself. The whole trick is that the state lives inside the closure, not outside: every time next() is called, the iterator knows where it is.
An easy detail to get wrong: when pushing children onto the stack, push them in reverse order, because a stack is LIFO — otherwise the eldest sibling gets visited last and your tree order gets scrambled in a very annoying way.
The line [Symbol.iterator]() { return this } makes the iterator an iterable, so it works with for...of and spread. This is exactly how generator objects behave.
let touched = 0
function preorder(root: Tree) {
const stack: Tree[] = [root] // <- state: no node seen yet
return {
next(): IteratorResult<string> {
const node = stack.pop()
if (!node) return { value: '', done: true }
touched++
for (const c of (node.children ?? []).slice().reverse()) stack.push(c)
return { value: node.value, done: false }
},
[Symbol.iterator]() { return this }, // the iterator is also an iterable
}
}index out into a module variable and two parallel loops will trip over each other.Try it: laziness, and "resume from where it stopped"
The three lines below prove both properties. Line 2: take the first 3 nodes and break — the touched variable shows the iterator touched exactly 3 nodes, not 7. Nobody pays for the part the user does not look at.
Line 3: the same iterator, after break, spread again — it continues from where it stands, it does not go back to the start. That is "stateful". To start over, call preorder(tree) again, i.e. ask for a new traversal.
console.log('generator : ' + [...walk(tree)].join(' > '))
const it = preorder(tree)
const first3: string[] = []
for (const v of it) {
first3.push(v)
if (first3.length === 3) break
}
console.log('first 3 : ' + first3.join(' > ') + ' (touched ' + touched + '/7 nodes)')
console.log('resume : ' + [...it].join(' > '))generator : app > components > Button.vue > Modal.vue > pages > index.vue > nuxt.config.ts first 3 : app > components > Button.vue (touched 3/7 nodes) resume : Modal.vue > pages > index.vue > nuxt.config.ts
Lazy for real: pagination with a page cursor
This is where Iterator earns its keep. A page generator only runs its body (i.e. calls the API) when the caller actually pulls a value. The user views three pages, exactly three pages get fetched, not 50. break is not "skip rendering" — it spends nothing.
The same shape works for cursor APIs: next() calls fetch(url + cursor) and takes the cursor from the response. When the data runs out, return — done: true, and the loop ends without ever knowing the total page count.
let fetched = 0
function* pages(pageSize: number, total: number): Generator<number> {
for (let p = 1; p * pageSize <= total; p++) {
fetched++ // only runs when the caller actually asks
yield p * pageSize // "now holding p*pageSize items"
}
}
const feed = pages(20, 1000)
let have = 0
for (const got of feed) {
have = got
if (have >= 60) break // never pays for page 4
}
console.log(have + ' items, ' + fetched + ' pages')60 items, 3 pages
Array.map/filter return every element right away. An iterator returns one element when asked. With large or remote data, "when asked" is the entire value.Compose a pipeline: BFS, filter, map — one iterator each, nestable
Because every step is an iterable, you compose them: filter(bfs(root), n => n.depth > 1) is a breadth-first traversal that only takes deep nodes, and it stays lazy end to end. No intermediate arrays get created. This is the hand-rolled version of an Observable/iterator-helpers pipeline.
Note that yield* delegates to anything with [Symbol.iterator], so your generator can consume other generators, Maps, Sets, NodeLists... without caring which.
function* bfs(root: Tree): Generator<string> {
const queue: Tree[] = [root]
while (queue.length > 0) {
const n = queue.shift()!
yield n.value
queue.push(...(n.children ?? [])) // FIFO -> same level first
}
}
function* filter<T>(source: Iterable<T>, keep: (x: T) => boolean): Generator<T> {
for (const x of source) if (keep(x)) yield x
}
for (const v of filter(bfs(root), x => x.endsWith('.vue'))) {
console.log(v) // reads like a description, still runs one at a time
}State pitfalls: once it is done it is done, and `break` triggers cleanup
An iterator does not reset itself. A second [...it] returns an empty array. This is not an engine bug — it is the definition. If you need to traverse again, ask for a new iterator; and if you write a cache that hands back the same iterator on every call, two nested loops will steal each other's position.
The flip side is something many people do not know: break/throw inside for...of makes the engine call iterator.return() if it exists. For generators, that runs finally immediately — meaning function* is a safe place to close connections, release locks, cancel subscriptions.
const it = [1, 2, 3][Symbol.iterator]()
console.log([...it].join(','), JSON.stringify([...it])) // '1,2,3' then '[]'
function* withCleanup(): Generator<number> {
try {
yield 1
yield 2
}
finally {
console.log('cleanup: generator has been closed')
}
}
for (const n of withCleanup()) {
if (n === 1) break // <- break calls return(), finally runs right away
}1,2,3 [] cleanup: generator has been closed
break: generators clean up per the contract, your try/finally will run.04 — Who talks to whom
Structure
- IterableWhere you **ask** for a traversal: has `[Symbol.iterator]()`. Stateless, hand out as many iterators as you like.
- IteratorThe traversal itself: has `next()` returning `{ value, done }`, plus `return()` if early close is allowed. It **is** the cursor.
- ConcreteIteratorPreorder (stack), BFS (queue), cursor (remote page + pointer). Each a different walking strategy, same contract.
- Collection / AggregateTree, list, remote dataset. Only knows how to create iterators, does not know who is traversing it.
- ClientRuns `for...of`, spread, `Array.from`, `yield*`. Only talks to the contract, never touches internal fields.
Client ──for...of──► Iterable ──[Symbol.iterator]()──► Iterator
│ │ holds state:
│ calls next() until done = true │ stack, index, cursor
│ break/throw → calls return() (if any) │ remembers where it is
└──────────── { value, done } ◄─────────────┘
Iterable = where you ASK for a traversal (stateless, ask freely)
Iterator = the traversal ITSELF (stateful, remembers progress)
Generator = both, written with function* + yield05 — Edit freely, run it right here
Try it: a generator, a hand-written iterator, and laziness
type Tree = { value: string, children?: Tree[] }
const tree: Tree = {
value: 'app',
children: [
{ value: 'components', children: [{ value: 'Button.vue' }, { value: 'Modal.vue' }] },
{ value: 'pages', children: [{ value: 'index.vue' }] },
{ value: 'nuxt.config.ts' },
],
}
/** Generator: values are only produced when the caller asks. */
function* walk(node: Tree): Generator<string> {
yield node.value
for (const child of node.children ?? []) yield* walk(child)
}
/** Hand-written iterator: has state (a stack) and remembers where it is. */
let touched = 0
function preorder(root: Tree) {
const stack: Tree[] = [root]
return {
next(): IteratorResult<string> {
const node = stack.pop()
if (!node) return { value: '', done: true }
touched++
for (const c of (node.children ?? []).slice().reverse()) stack.push(c)
return { value: node.value, done: false }
},
[Symbol.iterator]() { return this },
}
}
console.log('generator : ' + [...walk(tree)].join(' > '))
const it = preorder(tree)
const first3: string[] = []
for (const v of it) {
first3.push(v)
if (first3.length === 3) break
}
console.log('first 3 : ' + first3.join(' > ') + ' (touched ' + touched + '/' + [...walk(tree)].length + ' nodes)')
console.log('resume : ' + [...it].join(' > '))generator : app > components > Button.vue > Modal.vue > pages > index.vue > nuxt.config.ts first 3 : app > components > Button.vue (touched 3/7 nodes) resume : Modal.vue > pages > index.vue > nuxt.config.ts
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- Your collection is not a flat array: a tree, a graph, a table of contents, a folder tree, the DOM tree, nested JSON — and the caller just wants "give me the next one".
- The data is large or remote: you want
for...ofover 10,000 rows or over a paginated API without stuffing everything into memory before you start. - You need several traversal strategies over the same data (preorder, BFS, leaves only, skip hidden nodes) without copying the loop.
- You want to encapsulate the storage structure: switch an array to a Map, or memory to a stream, without touching the UI code that traverses it.
- You need several parallel loops over the same collection, or need to pause/resume a traversal over time (scroll-load, batch jobs, pausable processes).
Don't use it when
- Over-engineering. Your collection is a
T[]with only one way to traverse it? Just loop over the array withfor...of, it is already an Iterator. Writing an Iterator class for anitems: Order[]is the signature of someone who just finished a patterns book. - Iterators are one-shot. Store one in state/a store and reuse it for a second traversal and you silently get empty results. Ask for a new iterator every time.
- Mixing up
for...inandfor...ofis a classic bug:for...inyields string keys and climbs the prototype chain, so using it on an array invites index bugs and stray keys;for...ofrequires the iterable contract, sofor...of {}throws immediately. The right bridge for plain objects isObject.entries(obj)— it returns an array, so it is iterable, and only includes the object's own keys. Map/Setiterators are live: modifying the map during traversal is visible to the traversal (deleting an element not yet reached makes it get skipped). With arrays,for...ofreadslengthand the index on each step, so splicing midway shifts the indices. To be safe: snapshot ([...map.keys()]).- Lazy is not free:
for...ofover a remote generator runs sequentially, each step waiting for a round-trip. To keep a pipeline fast you need async iterators (for await...of) or to batch thenext()calls yourself. Do not use a remote generator and then cry about why 5,000 items take 5,000 pings.
07 — You have met it already, just not by name
In real code
for...of, spread, destructuring, Array.from, new Map(entries)
They all just call Symbol.iterator() and then next() until done. That is why const [a, b] = new Set(xs), [...new Set(arr)], Array.from(document.querySelectorAll("li")), new Map(Object.entries(o)) all work across different types: they speak the same contract.
Iterable and non-iterable types in JS
Iterable: Array, String, Map, Set, typed arrays, generators, NodeList, URLSearchParams, FormData. Not iterable: plain Object and HTMLCollection — so document.getElementsByClassName("box") needs Array.from(...) or [...] before you can spread it. Note that Map is iterable but iterating it directly gives [key, value] pairs: if you need keys or values, call .keys() / .values().
Cursor pagination + streams in Node
Modern APIs return a cursor/next_token instead of an offset. The iterator shape: next() fetches a page, yields items one by one, fetches the next page when the current one runs out — the caller only sees for...of. Node also accepts iterables/async iterables directly: Readable.from(asyncFunction*()) and for await (const chunk of res.body) with fetch in Node 18+.
Vue/Nuxt: lazy lists and paged useAsyncData
Infinite scroll/cursor loading is an iterator dressed up as a composable: the state (cursor, loaded yet or not) lives in the closure of useAsyncData/the composable, loadMore() is next(), and done is hasMore === false. Writing it as a generator + for await separates "fetching data" from "rendering" — the same encapsulation benefit.
08 — Try it yourself
Exercise
Make your `Tree` **iterable** without changing how it stores `children`: add `[Symbol.iterator]()` (preorder) and a `*leaves()` generator that only yields leaf nodes. Check that `[...app]`, `[...app.leaves()]`, and `for (const v of app) { if (...) break }` all work, and that two nested loops do not step on each other.
Hints, open them one at a time:
- Where does the traversal state go? Hint: inside the closure of
[Symbol.iterator]()itself, not on the instance — if it lives on the instance, two nested loops will overwrite each other's cursor. - You need
slice().reverse()before pushing children onto the stack, otherwise sibling order gets flipped. (Or switch toqueue.shift()if you want BFS.) *leaves()does not need a stack: onlyyieldwhenchildren.length === 0, otherwiseyield*into the subtree.
[Symbol.iterator]() creates a fresh stack in its closure on every call and returns an iterator that remembers its own position — which is why two nested loops stay independent. *leaves() is a recursive generator using yield*. Neither touches the storage structure, so you can switch children to a Map without callers ever knowing.
class Tree {
constructor(public value: string, public children: Tree[] = []) {}
[Symbol.iterator](): Iterator<string> {
const stack: Tree[] = [this] // SEPARATE state for each traversal
return {
next(): IteratorResult<string> {
const n = stack.pop()
if (!n) return { value: undefined as unknown as string, done: true }
stack.push(...n.children.slice().reverse())
return { value: n.value, done: false }
},
}
}
*leaves(): Generator<string> {
if (this.children.length === 0) yield this.value
else for (const c of this.children) yield* c.leaves()
}
}
const app = new Tree('app', [
new Tree('pages', [new Tree('index.vue')]),
new Tree('nuxt.config.ts'),
])
console.log([...app].join(' > ')) // app > pages > index.vue > nuxt.config.ts
console.log([...app.leaves()].join(', ')) // index.vue, nuxt.config.ts09 — Read them in pairs to see the essence
Related patterns
- CompositeA tree is a Composite, and preorder/BFS iterators only work because every node has the same type. These two patterns almost always show up together.
- StrategyPreorder, BFS, leaves-only, skip-hidden-nodes are **traversal strategies** placed behind the same `next()` contract. Iterator is Strategy for walking.
- Chain of ResponsibilityBoth decouple the caller from the handler, but along different axes: CoR answers "who handles this", Iterator answers "which one comes next".
- MementoIf you want to **pause and resume** a traversal (or rewind it), the iterator's state is exactly what needs saving — Memento is the name for that.