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
breakorreturn) - 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...ofloop exits viabreakorreturn - 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.