Lesson 18. Generator functions

 

After reading lesson 18, you will

  • Know how to define generator functions
  • Know how to yield values from generator functions
  • Understand the generator function lifecycle

Generator functions are one of the harder things to comprehend among all the recent additions to JavaScript. They introduce a new form of code execution and processing that most JavaScript developers haven’t seen before. Generators aren’t new concepts, though—they’re already part of Python, C#, and other languages. This lesson is only meant to be a gentle introduction to the topic.

You’ll see how good generators are at creating lists, but that isn’t all generators are good for. That would be like saying objects are only useful for storing key/value pairs. To the contrary, generators, like objects, are a powerful multipurpose tool that can be used for all sorts of problems. For example, we’ll see how useful they can be for working with iterable and asynchronous tasks later on in Units 5 and 7. For now, though, you need to master the basics.

Consider this

Inside of a function, once you return a value, the rest of the function is no longer processed and the function exits. This means the return statement stops the function from going any further. What if you could return a value, but only pause the function at that point instead of exit, and then later tell the function to continue where it left off?

18.1. Defining generator functions

18.2. Using generator functions

18.3. Creating infinite lists with generator functions

Summary