Sub topic 7
Early Exit and the return() Method
This chapter assumes you can write a custom iterable by hand, as shown in the previous chapter, and that you know how for...of and destructuring consume iterables.
An iterator may hold a resource while it runs, such as an open file handle, a database cursor, or a timer. If the consumer reads every value, the iterator knows it has finished and can release the resource itself. Many consumers stop early, though. JavaScript handles this case with an optional iterator method, return().
When return() is called
return() tells the iterator that the consumer will not call next() again. The language calls it automatically when a consumer stops before the iterator reports done: true.
| Situation | Is `return()` called? |
|---|---|
| `break` inside `for...of` | Yes |
| `return` from a function inside the loop body | Yes |
| An exception thrown in the loop body | Yes, then the error keeps propagating |
| Destructuring that takes fewer values than exist, e.g. `const [a] = it` | Yes |
| The loop runs until `done: true` | No |
| Spread or `Array.from` reading every value | No |
A cleanup-aware iterator
function withCleanup(items) {
let i = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
return i < items.length
? { value: items[i++], done: false }
: { value: undefined, done: true };
},
return() {
console.log('cleanup');
return { value: undefined, done: true };
}
};
}
for (const x of withCleanup([1, 2, 3])) {
if (x === 2) break; // logs 'cleanup'
}
const [first] = withCleanup([1, 2, 3]); // logs 'cleanup'
console.log(first); // 1
console.log([...withCleanup([1, 2])]); // [ 1, 2 ] and no 'cleanup'In the last line, spread reads every value until done: true, so the iterator ended normally and return() is never called. If an iterator must release a resource in every case, it has to clean up in two places: in next() when it runs out of values, and in return().
Common errors
- Returning a non-object.
return()must return an object. If it returnsundefined,for...ofthrows aTypeErrorafter abreak. - Expecting return() on normal completion. It is not called when the iterator finishes by itself. Put that cleanup in
next(). - Reusing an iterator after closing it. Once
return()has been called, laternext()calls should reportdone: true. Consumers should not rely on getting more values. - Swallowing errors. If the loop body throws, the original exception propagates after
return()runs. Areturn()that throws its own error during an exception is ignored in favor of the original error.
Exercise
Given the withCleanup function above, how many times is 'cleanup' logged by this code: const [a, b] = withCleanup([1, 2]); for (const x of withCleanup([5])) {}?
Show answer
Zero times. The destructuring takes two values from a two-item iterator but never sees done: true, so it does call return(). That makes one log. The loop runs until done: true and does not call return(). The total is one log, not zero: destructuring closes the iterator whenever it stops before seeing done: true, even if no values remain.
Exercise
Why does a TypeError occur if return() is written as return() { console.log('bye'); } and the loop uses break?
Show answer
The method returns undefined. The language requires return() to return an object, so after calling it, for...of throws a TypeError.