Iterating Over Custom Collections
You'll learn how to create iterators for non-array data structures like linked lists and trees.
So far, you've implemented iterators for simple objects and ranges. But what about more complex data structures? Real-world applications often use linked lists, trees, graphs, or other custom collections that don't store data in sequential memory like arrays do. The iterator protocol lets you make any data structure work seamlessly with for...of, spread, and destructuring.
Why Custom Collections Need Iterators
A linked list stores data in nodes that point to each other. A tree has parent-child relationships. These structures don't have numeric indexes like arrays, but they still contain data you want to traverse. By implementing Symbol.iterator, you define how to walk through your custom structure—node by node, depth-first, breadth-first, or any way you choose.
The Core Pattern
Your Symbol.iterator method returns an iterator object with a next() method. Inside next(), you maintain state (like the current node position) and return the next value from your collection until you're done.
For example, in a linked list, you'd start at the head node, return its value, move to the next node, and repeat. For a tree, you might use a stack or queue to track which nodes to visit next, depending on your traversal order.
Key Takeaway: By implementing Symbol.iterator on custom data structures, you make them first-class citizens in JavaScript's iteration ecosystem, enabling traversal through any structure—simple or complex—with familiar syntax.