Tip #4 [Iterables]

JavaScript ships with several built-in iterables, namely Array, String, Map and Set instances. When such an object needs to be iterated over, its iterator provides successive elements:

However, you’re not limited to the built-in ones only, since you can make any object an iterable by implementing the Symbol.iterator method, which has to return an object conforming to the iterator protocol.

Let’s take a look at exemplary linked list class:

Let’s define auxiliary interfaces:

and a linked list’s iterator class:

In the next step, let’s make LinkedList instances iterable by implementing the required method:

Live example:

If you like the tip, please give me some applause 👏

--

--