The syntax is very similar to what we see in a for loop. We declare a variable with let, const, or var and the loop will iterate over each item in array, or other iterable type, we specify. Generally, const will be the most appropriate choice, as there should be no reason to override the variable reference specified within the loop. The example below shows how we can use this for an array:
In the next section, we will introduce the iterable protocol and outline how to use it with classes to allow use of for..of over them.
[Symbol.iterator](). This is similar in concept to a class implementing an interface. The code below shows an example of a custom iterable class which allows for iteration over an array:
Notice in the code above, we are returning an object with a function next, which in turn returns properties value and done. This is the type of object which must be returned by this protocol. However, in the sections below, we'll outline a simpler way of declaring iterables so you do not need to do this.
Iterables with Generators
[Symbol.iterator]() declaration; this is how we specify that it will be a generator function:
This time, instead of returning an object which has a function which returns another object, we can simply yield values as we move through them. This is one of the simplest approaches, and is the approach we will take in the rest of this article. In the sections below, we'll implement a few more iterables with some different types of examples:
Example: Iterate over Words in a String
In this example, we'll create an iterable class which will take a string and allow the consumer to iterate over a word at a time. We'll define a word as a sequence of characters with no spaces; we will not check if they are actual valid words:
Example: Perform a Breadth First Search
In this example, we will accept a binary tree's root node in the constructor, then have our iterable perform a breadth-first search and yield each node value along the way. For a brief introduction to binary trees, please visit our introduction to binary trees dev page.