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

Early Termination with return()

Implement the optional return() method to handle cleanup when iteration stops early.

Early Termination with return()

You'll learn how to implement the optional return() method on iterators to handle cleanup when iteration stops before completion.

Why Iterators Need Cleanup

When you use for...of or spread operators, iteration doesn't always run to the end. A break statement, an exception, or simply destructuring fewer items than available can all stop iteration early. The iterator protocol provides a way to detect this and clean up resources.

The return() Method

An iterator can implement an optional return() method that gets called automatically when iteration terminates early. This method should:

  • Accept an optional argument (usually the value passed to break or return)
  • Return an iterator result object (typically { done: true, value: undefined })
  • Perform any necessary cleanup
function createResource() {
  console.log('Opening resource...');
  let current = 0;
  
  return {
    [Symbol.iterator]() { return this; },
    
    next() {
      if (current < 5) {
        return { value: current++, done: false };
      }
      return { done: true };
    },
    
    return() {
      console.log('Cleaning up resource...');
      return { done: true };
    }
  };
}

for (let num of createResource()) {
  console.log(num);
  if (num === 2) break;  // Triggers return()
}
// Output:
// Opening resource...
// 0
// 1
// 2
// Cleaning up resource...

When return() Gets Called

The return() method fires when:

  • A for...of loop exits via break or return
  • An error occurs during iteration
  • Destructuring takes fewer values than available

Key Takeaway: Implement the optional return() method on your custom iterators to handle cleanup tasks like closing files, releasing locks, or freeing resources when iteration stops before reaching the natural end.