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

Calling a Generator Function

Understanding that calling a generator returns a generator object, not executing the function body immediately.

Calling a Generator Function

What you'll learn: How calling a generator function doesn't execute its code right away — it returns a special object instead.

The Surprising First Step

When you call a regular function, JavaScript immediately runs the code inside its body. Generator functions behave differently. Calling a generator function does not execute any of its code. Instead, it returns a generator object — a special kind of iterator that will control the function's execution later.

Think of it like pressing "play" on a media player versus loading the media file. Calling a generator is like loading the file: you get a controller (the generator object) but nothing plays yet. You still need to manually press "play" by calling methods on that controller.

function* countToThree() {
  console.log('Starting...');
  yield 1;
  yield 2;
  yield 3;
}

// Calling the generator function
const generator = countToThree();

// Notice: "Starting..." hasn't logged yet!
// The function body hasn't run at all.

console.log(generator); // Object [Generator] {}

What You Get Back

The generator object implements the iterator protocol you've already learned. It has a next() method, which you'll use to actually step through the generator's code. Until you call next(), the generator function sits idle — none of its code executes.

This "lazy execution" behavior is what makes generators powerful. You create the controller first, then decide when and how to advance through the function's steps.

Key Takeaway: Calling a generator function returns a generator object without executing the function body — execution only begins when you interact with the returned object.