Generators

Learn about ES2015 generators, a new type of function. Learn how to pause a function and dynamically change its state. These allow us to get multiple values out of a function.

Generators are functions that maintain their own internal state. A generator works as a factory for iteratables. They return a Generator object, which is both an iterable and an iterator. That is, they can be iterated using for-of loops and the spread operator, and they can be iterated through manually using next.

Generators

Creating a Generator

A generator is created by declaring a function with a special character: *.

function* generator() {}

yield

Instead of using return statements, generators use a new keyword, yield. We can yield values from a generator multiple times. The values we yield are used as if they were coming from an iterable.

Get hands-on with 1200+ tech skills courses.