...

/

Iterator Pattern

Iterator Pattern

Learn how to implement the Iterator protocol.

We'll cover the following...

The Iterator pattern is a fundamental pattern and it’s so important and commonly used that it’s usually built into the programming language itself. All major programming languages implement the pattern in one way or another, including, of course, JavaScript (starting from the ECMAScript2015 specification).

The Iterator pattern defines a common interface or protocol for iterating the elements of a container, such as an array or a tree data structure. Usually, the algorithm for iterating over the elements of a container is different depending on the actual structure of the data. Think about iterating over an array vs. traversing a tree: in the first situation, we need just a simple loop; in the second, a more complex tree traversal algorithm is required. With the Iterator pattern, we hide the details about the algorithm being used or the structure of the data and provide a common interface for iterating over any type of container. In essence, the Iterator pattern allows us to decouple the implementation of the traversal algorithm from the way we consume the results (the elements) of the traversal operation.

In JavaScript, however, iterators work great even with other types of constructs, which are not ...