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

Early Termination with return()

Using the generator's return() method to force completion and optionally provide a final value.

Early Termination with return()

You'll learn how to forcefully complete a generator from the outside using its return() method.

The Core Idea

While next() lets you step through a generator normally, sometimes you need to shut it down early. The generator object's return() method lets you do exactly that—it completes the generator immediately and optionally provides a final value, just like hitting an emergency stop button.

When you call return(value) on a generator:

  1. The generator stops executing wherever it is
  2. It returns { value: value, done: true }
  3. Any subsequent next() calls return { value: undefined, done: true }

How It Works

function* countdown() {
  yield 3;
  yield 2;
  yield 1;
  yield "Liftoff!";
}

const counter = countdown();

console.log(counter.next());        // { value: 3, done: false }
console.log(counter.return("ABORT")); // { value: "ABORT", done: true }
console.log(counter.next());        // { value: undefined, done: true }
// Generator is now permanently closed

The generator never reaches the remaining yield statements. If you don't pass a value to return(), it defaults to undefined.

Real-World Analogy

Think of a generator as a music playlist. The return() method is like hitting the stop button—the playlist ends immediately, and you can optionally show a "Stopped by user" message. Even if you press play again, nothing happens because the playlist is finished.

Key Takeaway: Use return() on a generator to complete it immediately from the outside, optionally providing a final value—perfect for cleanup or cancellation scenarios.