Iterator Pattern with Closures
You'll learn how to build custom iterators that remember their position between calls using closures.
What Is an Iterator?
An iterator is an object that knows how to traverse a collection one item at a time. The key is that it maintains its current position internally, so each time you call next(), it picks up where it left off. Closures are perfect for this because they preserve private state across function calls.
Think of it like a bookmark in a book: the iterator remembers which page you're on, so you can close the book and come back later to the exact same spot.
Building a Custom Iterator
Here's a simple iterator factory that returns an object with a next() method:
function createIterator(array) {
let index = 0; // Private state, captured by closure
return {
next() {
if (index < array.length) {
return { value: array[index++], done: false };
}
return { value: undefined, done: true };
}
};
}
const iterator = createIterator(['a', 'b', 'c']);
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: 'c', done: false }
console.log(iterator.next()); // { value: undefined, done: true }
The index variable is trapped in the closure. Each call to next() accesses and updates that same index, allowing the iterator to track its position through the array.
Why This Works
The closure keeps index alive and private. No external code can reset it or read it directly—only the next() method can. Each iterator instance gets its own independent closure with its own index.
Key Takeaway: Closures let you build iterators that maintain hidden, persistent state across multiple next() calls, enabling controlled traversal of data structures.