Course contentsShow
← JavaScript
Lesson 1096 of 2,72325. Iterators and GeneratorsFree lesson

What Are Generator Functions?

Understanding generators as functions that can pause execution and resume, producing multiple values over time.

What Are Generator Functions?

You'll learn: How generator functions let you write functions that can pause mid-execution and resume later, producing values one at a time.

The Core Idea

Imagine a normal function as a one-way journey: once you call it, it runs from start to finish and returns a single value. A generator function is different—it's like a road trip with rest stops. You can pause the journey, hand back a value, and later continue exactly where you left off.

Generator functions let you produce multiple values over time instead of computing everything upfront and returning it all at once. Each time you resume the generator, it picks up where it paused, runs until the next pause point, yields another value, and waits again.

How They Differ From Regular Functions

Regular functions execute completely in one go. Generator functions:

  • Can pause execution using yield
  • Resume from where they paused when asked
  • Produce a sequence of values rather than a single return
  • Return an iterator that follows the iterator protocol you just learned

Think of a generator as a factory assembly line you control: you tell it "give me the next item," it produces one piece, then waits until you ask again.

Why This Matters

Generator functions bridge the gap between writing imperative code (with loops and state) and producing iterable sequences. Instead of building an entire array upfront, you can generate values on-demand, which is memory-efficient and powerful for large or infinite sequences.

Key Takeaway: Generator functions are special functions that can pause and resume execution, yielding multiple values over time through the iterator protocol—making them perfect for creating custom, lazy sequences.