Course contentsShow
← JavaScript
Lesson 2012 of 2,72342. Iteration Protocols Deep DiveFree lesson

The Iterator Return Method

Optional return() method is called when iteration exits early (break, return, throw).

The Iterator Return Method

You'll learn how the optional return() method lets iterators clean up resources when iteration stops early.

What Is the Iterator Return Method?

When you create a custom iterator, you can optionally provide a return() method. This method gets called automatically when iteration exits before the iterator is exhausted—such as when code encounters a break, return, or throw statement inside a loop.

Think of return() as a cleanup crew: if someone walks out of a movie theater early, the cleanup crew needs to know so they can tidy up that specific row right away instead of waiting until the end.

Why It Matters

Without return(), your iterator has no way to know iteration stopped early. This matters when you're managing resources like file handles, database connections, or event listeners that need explicit cleanup.

const range = {
  [Symbol.iterator]() {
    let current = 1;
    return {
      next() {
        if (current <= 5) {
          return { value: current++, done: false };
        }
        return { done: true };
      },
      return() {
        console.log("Cleanup: iteration stopped early!");
        return { done: true };
      }
    };
  }
};

for (const num of range) {
  console.log(num);
  if (num === 3) break; // This triggers return()
}
// Logs: 1, 2, 3, then "Cleanup: iteration stopped early!"

The return() method must return an iterator result object (with done property). Even if iteration completes normally without calling return(), that's perfectly fine—it's truly optional.

Key Takeaway: The return() method gives your iterator a chance to perform cleanup when iteration exits early via break, return, or throw, making resource management safer and more predictable.