Generators Pattern

Learn how to create a simple generator function, pass values back to a generator, and use a generator in place of a standard iterator.

The ES2015 specification introduced a syntax construct that’s closely related to iterators. We’re talking about generators, also known as semicoroutines. They’re a generalization of standard functions, in which there can be different entry points. In a standard function, we can have only one entry point, which corresponds to the invocation of the function itself, but a generator can be suspended (using the yield statement) and then resumed at a later time. Among other things, generators are very well suited to implement iterators, in fact, as we’ll see in a bit, the generator object returned by a generator function is indeed both an iterator and an iterable.

Generators in theory

To define a generator function, we need to use the function* declaration (the function keyword followed by an asterisk).

Get hands-on with 1400+ tech skills courses.