O'Reilly logo

Rediscovering JavaScript by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required