Skip to Main Content
Rediscovering JavaScript
book

Rediscovering JavaScript

by Venkat Subramaniam
June 2018
Beginner content levelBeginner
288 pages
6h 31m
English
Pragmatic Bookshelf
Content preview from Rediscovering JavaScript

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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Object-Oriented JavaScript - Third Edition

Object-Oriented JavaScript - Third Edition

Stoyan STEFANOV, Ved Antani
Deno Web Development

Deno Web Development

Alexandre Portela dos Santos

Publisher Resources

ISBN: 9781680506174Errata Page