Tip 41: Create Iterable Properties with Generators

In this tip, you’ll learn how to convert complex data structures to iterables with generators.

In Tip 14, Iterate Over Key-Value Data with Map and the Spread Operator, you learned how simple it is to loop over maps thanks to iterables. And once you can iterate over a collection, you have access to the spread operator, array methods, and many other tools to transform your data. Iterables give your data more flexibility by allowing you to access each piece of data individually.

You also know that objects don’t have a built-in iterator. You can’t loop over an object directly—you need to convert part of it to an array first. That can be a major problem when you want the structure of an object but the flexibility of an iterable.

In this tip, you’ll learn a technique that can make complex data structures as easy to use as simple arrays. You’re going to use a new specialized function called a generator to return data one piece at time. In the process, you’ll see how you can convert a deeply nested object into a simple structure.

Generators

Generators aren’t exclusive to classes. They’re a specialized function. At the same time, they’re very different from other functions. And while the JavaScript community has enthusiastically embraced most new features, they haven’t quite figured out what to do with generators. In late 2016, a poll by Kent Dodds, a popular JavaScript developer, found that 81 percent of developers rarely or never used generators.

That’s changing. Developers and library authors are discovering how to use generators. One of the best use cases so far is to use generators to transform objects into iterables.

What is a generator? The Mozilla Developer Network explains that a generator is a function that doesn’t fully execute its body immediately when called.

Get hands-on with 1000+ tech skills courses.