Using Custom Iterators and Generators

The built-in collections in JavaScript, like Array, Set, and Map, are all iterable. We can iterate over them, using the for loop, to process the elements. But what about user-defined classes? You may create, for example, a Car class and may want the user of your class to iterate over its wheels or doors. Thankfully, JavaScript makes it quite easy to define custom iterators for user-defined classes. Before we jump in to writing custom iterators, let’s examine iterators for built-in classes.

We can easily iterate over a collection of objects. For example, the following code iterates over an array of strings:

​ ​const​ names = [​'Tom'​, ​'Jerry'​, ​'Tyke'​];

Get Rediscovering JavaScript now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.