Using a Generator to Define a Custom Iterator

Generator functions enhance the process of defining the iterable protocol by providing an iterative algorithm. When called, a generator function doesn’t execute its body immediately. Instead, it returns a special type of iterator known as a generator object, as shown in the following image.

images/generators/Generator.png

We can run the generator function’s body by calling its next() method. The yield keyword pauses the generator and specifies the value to be returned. With that in mind, let’s adapt the example in Creating a Custom Iterator. The result of this code is identical, but it’s much easier to implement.

Notice the asterisk ...

Get Modern Asynchronous 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.