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'​];
 
 for​(​const​ name ​of​ names) ...

Get Rediscovering JavaScript now with O’Reilly online learning.

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