Understanding Iterator Pattern in JavaScript/Typescript using Symbol.Iterator
Tags: javascript, typescript, patterndesign, cleancode
Published: 2019-06-20 13:40:02

---
title: Understanding Iterator Pattern in JavaScript/Typescript using Symbol.Iterator
published: true
description: In some languages there are high-level control structures that allow you to iterate the objects without having to create the **Iterator pattern** (since they provide it by default). However, it may be useful to modify this internal pattern to use the full potential of the language without the need for great verbosity, as in JAVA. It is essential to know about the Iterator pattern and to have read the article that I wrote, since the examples that will illustrate this article come from the previous one.
tags: javascript, typescript, pattern-design, clean-code
cover_image: https://cdn-images-1.medium.com/max/2428/0*GXFj7GBzekOSaF1x.jpg
canonical_url: https://www.carloscaballero.io/understanding-iterator-pattern-in-javascript-typescript-using-symbol-iterator
---


In the [Design Patterns series](https://www.carloscaballero.io/understanding-software-design-patterns-serie/) that I am writing to illustrate the 23 design patterns of the band of four (GoF) in a friendly way I recently wrote about the [Iterator pattern](https://medium.com/swlh/understanding-design-patterns-iterator-using-dev-to-and-medium-social-networks-25c453b083ac). This pattern has an incredible potential to decouple our data structure from the algorithms.

This pattern is widely implemented in different programming languages, for example, JAVA has the **Iterable Interface**.

In some languages there are high-level control structures that allow you to iterate the objects without having to create the **Iterator pattern** (since they provide it by default). However, it may be useful to modify this internal pattern to use the full potential of the language without the need for great verbosity, as in JAVA.

It is essential to know about the [Iterator pattern](https://carloscaballero.io/design-patterns-iterator/) and to have read the article that I wrote, since the examples that will illustrate this article come from the previous one.

ES6 introduces a new way to interact with JavaScript data structures  — iteration. There are 2 core concepts for Iterator Pattern:

 1. **Iterable** is a data structure that provides a way to expose its data to the public. In JavaScript the implementation is based on a method whose key is *Symbol.iterator*. Really, Symbol.iterator is a factory of iterators.

 2. **Iterator** is a structure that contains a pointer to the next element in the iteration.

Therefore, an iterable must be an object with a function iterator whose key is Symbol.iterator.

![](https://cdn-images-1.medium.com/max/2000/1*9SB92sVK0TKaP6OM2xnowg.png)

Furthermore, an iterator must be an object with a function named next that returns an object with the keys:

 1. value: the current item in the iteration

 2. done: true if the iteration has finished, false otherwise.

![](https://cdn-images-1.medium.com/max/1000/1*A6Rl8bgXt7YNYIkEiH8ZVA.png)

So, the previous code defines an iterable and an iterator which are used in the following way:

![](https://cdn-images-1.medium.com/max/2336/1*iUEGIJb-W0_-Bwl8xY-83A.png)

When you use a for-of loop the language is using an iterable, and creating its iterator. It keeps on calling the next() until done is true.

There are a list of iterables in JavaScript which are using the concepts previously mentioned natively.

 1. Arrays and TypedArrays over each element inside array.

 2. Strings over each character.

 3. Sets over their elements.

 4. Maps over its key-value pairs.

Some other constructs in JavaScript that use iterables are the following ones:

![](https://cdn-images-1.medium.com/max/2000/1*3SUNH-jvX1OaL_9tMbRf3w.png)

![](https://cdn-images-1.medium.com/max/2200/1*p2DximEvaiItlsmoMDomOQ.png)

I will now show you how you can implement this pattern using JavaScript/TypeScript Symbols. In our case, I have made up a problem in which there is a class named WordsCollection which defines a word's list ( items) and its set of methods to get and add (getItems and addItem). This class is used by the client using control structures, such as for or forEach. The following UML diagram shows the scenario that I have just described using the classical iterator pattern.

![](https://cdn-images-1.medium.com/max/2146/0*4UfhA3tic0ZeDYaB.jpg)

Now I’m going to show you the new UML diagram which maintains the compatibility with custom iterators and implements the native ones.

![](https://cdn-images-1.medium.com/max/2896/0*SpMtRjShyX2irpGt.jpg)

First, let’s start with the client that will use the iterator natively without the need to instantiate any classes. It will perform the iteration directly from the for-of loop.

![](https://cdn-images-1.medium.com/max/2608/1*e7j2i5U0jyy6XP-APOTQ5A.png)

Note that the native use of iterators on a language cleaner, since it is integrated with the control structures of the programming language.

The WordsCollection code associated is the following one:

![](https://cdn-images-1.medium.com/max/2976/1*E1nQW2pru0u_5LvRpTlAnQ.png)

The first thing we have to observe is that we need to implement two interfaces:

 1. **Aggregator** is used for custom Iterable and defines the necessary methods for the object to be iterable. Here we have to implement the constructor methods of the iterators.

 2. **Iterator** is used by the language natively, and is the one that defines the function [Symbol.iterator]: ().

The keys to the native iterator are the factory functions of the native iterator, which instead of directly implementing it has been extracted in a new class to keep the code as clean as in the previous solution ( NativeAlphabeticalOrderIterator).

![](https://cdn-images-1.medium.com/max/2840/1*62rCLfhJ7Oyj0JuzTqKdug.png)

Finally, both the native iterator and the custom iterator extend their next() method from an abstract iterator which implements the rest of the methods. The main difference between the next() methods from the iterators are the values returned by each one of them, since in the native iterator the Iterator interface must be satisfied, which returns an IteratorResult while the CustomIterator returns the value directly.

This code could even be refactored to be used together with other design patterns such as [Template-Method](https://carloscaballero.io/design-patterns-template-method/) or [Strategy](https://carloscaballero.io/stategy-pattern-in-javascript-typescript/). However, I think it is better not to further complicate the example with the addition of these patterns.

![](https://cdn-images-1.medium.com/max/3348/1*fpQhe6wjOtW44nrzCEmRAA.png)

The client is decoupled from the internal structure of the WordsCollection class ( *Single Responsibility*) and you can extend the software implementing new iterators ( *Open/Closed*).

I have created two npm scripts that run the code example shown here after applying the Iterator pattern.

npm run example1-problem
npm run example1-iterator-solution-1

The following example is described extensively in the following article, therefore I recommend that you [read this article](https://carloscaballero.io/design-patterns-iterator/) to understand this. However, just to give you an idea of what we are developing I will give you a brief description of the problem.

Imagine that we have to create a software that allows us to send emails to our contacts in social networks, taking into account that we are going to differentiate the type of mail to send. In our network of contacts we have two categories of contacts: Friends and Coworkers. The email to be sent will be more formal depending on the type of contact to which the email will be sent.

At first we have contacts from two famous social networks: Dev.to and Medium. The implementation of the data structure of each of the social networks is different, since in Dev.to an array is used to maintain the contacts while in Medium a Map is used.

You can find a gif below showing the client using our entire structure (I have done a small CLI example).

![](https://cdn-images-1.medium.com/max/2000/0*SYr5M9EO9UIBZxvm.gif)

In the following UML diagram you can see the solution proposed for this problem using CustomIterator:

![](https://cdn-images-1.medium.com/max/2428/0*GXFj7GBzekOSaF1x.jpg)

The diagram associated with the solution that includes native iterators is as follows. In any case, we continue to maintain compatibility with custom iterators.

![](https://cdn-images-1.medium.com/max/2336/0*oi9coPqmVqfMJGJo.jpg)

The main advantages of developing decoupled software is that, as our software grows, it is not affected by the changes. In fact, the client of our application is still the same piece of code since it is built based on interfaces and using dependency injection.

![](https://cdn-images-1.medium.com/max/3584/1*tVMGu3IDbQSwyosVl0UAUg.png)

The sendSpamToFriends and sendSpamToCoworkers methods use the iterators, either custom or native.

![](https://cdn-images-1.medium.com/max/3244/1*hYv380IDwsoBNeFhIYS9Tg.png)

In this method we use custom and native iterators. The creation of the native iterators has been delegated to an iterators’ factory to discern between friends or coworkers.

The social networks (dev.to or medium) must satisfy the SocialNetwork interface by creating the native iterator through the object of the Iterable <Profile> type. The code associated to the social networks is the following one:

![](https://cdn-images-1.medium.com/max/3448/1*Pb61cugkh3PbIPPuPw9NEw.png)

![](https://cdn-images-1.medium.com/max/3480/1*UomKF-Nt40_9sYdQMkgKYg.png)

Each of the social networks (dev.to or medium) must satisfy the SocialNetwork interface by creating the native iterator through the object of the Iterable type <Profile>.

Below is the code associated with the iterators. Both iterators (custom and native) extends from a parent iterator where the methods in common have been implemented. Although the Iterator interface has several methods in our example, we only need to implement the next() method.

![](https://cdn-images-1.medium.com/max/3380/1*BdQ9bfthOaBDY9vihHWrGA.png)

The iterators associated to medium correspond to the same interface as those of dev.to and are shown below:

![](https://cdn-images-1.medium.com/max/3180/1*Otzc8d8U0BCDiKAdDWMWrQ.png)

I have created an npm script that runs the example shown here after applying the Iterator pattern and a CLI interface.

npm run example2-iterator-solution1

Iterator pattern can avoid coupled code in your projects. When there are several algorithms and data structures in a collection the iterator pattern is perfectly adapted. Your code will be cleaner, since you apply two famous principles, such as **Single Responsibility** and **Open/Closed**.

Sometimes we are interested in knowing the programming language on which we are developing and check if the **Iterator pattern** is inherently implemented as it happens in languages such as JavaScript (shown throughout this post), Python or PHP.

The most important thing is not to implement the pattern as I have shown you, but to be able to recognise the problem which this specific pattern can resolve, and when you may or may not implement said pattern. This is crucial, since implementation will vary depending on the programming language you use.

*Originally published at [https://www.carloscaballero.io](https://www.carloscaballero.io/understanding-iterator-pattern-in-javascript-typescript-using-symbol-iterator) on June 20, 2019.*