> For the complete documentation index, see [llms.txt](https://khaled-hamam.gitbook.io/design-patterns-explained/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://khaled-hamam.gitbook.io/design-patterns-explained/library/behavioral-patterns/iterator.md).

# Iterator Pattern

## Intent

Provide a way to access the elements of a collection without exposing the underlying representation.

## When to use

1. When your collection has a complex data structure under the hood, but you want to hide its complexity from clients (either for convenience or security reasons).
2. To support multiple traversal techniques for a collection.
3. You want to provide a uniform interface for traversing different types of collections (Polymorphic Iteration).
4. To reduce duplication of the traversal code across your app.

## Structure

![](https://2149973296-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MKKrm5lFe01Ro4BXbPp%2Fsync%2F1d1f608ca145a7cf2d3ad4bf2412f13f0700e6a7.png?generation=1603463578087281\&alt=media)

* Iterator: defines an interface for accessing and traversing elements.
* ConcreteIterator: implements the iterator interface for a certain collection.
* IterableCollection: defines an interface for creating an iterator object.
* ConcreteCollection: keeps track of the current object (data structure).

## Notes

Most of the programming languages provide their own ways of implementing iterators. TypeScript (and JS of course) provide an interface for the Iterators, and a Symbol in the class to create the iterators so the Collection will be able to participate in for..of loops (check example 2 and 3). Also generator functions return iterators so they can be used as iterators (Check example 3).

## Examples

|                                                                           Source Code                                                                           |   UML   |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----: |
| [Example 1](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/behavioral-patterns/iterator/example_1.ts) | // TODO |
| [Example 2](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/behavioral-patterns/iterator/example_2.ts) | // TODO |
| [Example 3](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/behavioral-patterns/iterator/example_3.ts) | // TODO |

You can find the tests [here](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/behavioral-patterns/iterator/index.test.ts).
