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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.