Sub topic 7
Early Exit and the return() Method
This chapter assumes you know how to write a custom iterable by hand, with a next() method that returns { value, done } objects, and that you know which language features consume iterables. Here you will add the third, optional iterator method, return(), and learn exactly when JavaScript calls it.
Why iterators need a cleanup hook
Some iterators hold resources: a file handle, a database cursor, a network connection, a timer. When the consumer reads every value, the iterator knows it is finished because it is the one producing done: true. It can release resources at that moment.
Consumers often stop early, though. A for...of loop hits break, a search function returns once it finds a match, or the loop body throws. In each case the iterator never reaches its end, so without help it would never learn that nobody wants more values. The resource would stay open.
The iterator protocol handles this with an optional method, return(). When a language construct abandons an iterator before it is done, it calls iterator.return() if that method exists. The spec calls this step IteratorClose.
A tracing iterator
To see when return() runs, use an iterator that logs every call:
function traced(items) {
let i = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
if (i < items.length) {
return { value: items[i++], done: false };
}
return { value: undefined, done: true };
},
return() {
console.log(`return() called after ${i} value(s)`);
i = items.length; // mark as finished so later next() calls report done
return { value: undefined, done: true };
}
};
}
// 1. break
for (const x of traced([1, 2, 3])) {
if (x === 2) break;
}
// return() called after 2 value(s)
// 2. Running to completion: return() is NOT called
for (const x of traced([1, 2, 3])) {}
// (no output)
// 3. continue does not leave the loop, so no call
for (const x of traced([1, 2, 3])) {
if (x === 2) continue;
}
// (no output)
// 4. return from the enclosing function
function findFirstEven(iterable) {
for (const x of iterable) {
if (x % 2 === 0) return x;
}
}
console.log(findFirstEven(traced([1, 2, 3, 4])));
// return() called after 2 value(s)
// 2
// 5. An exception thrown in the loop body
try {
for (const x of traced([1, 2, 3])) {
if (x === 1) throw new Error('boom');
}
} catch (e) {
console.log('caught', e.message);
}
// return() called after 1 value(s)
// caught boomThe rule is simple. return() runs whenever control leaves the loop for any reason other than the iterator reporting done: true.
Which consumers call return()
for...of is not the only consumer that closes iterators. Anything that stops pulling early does the same.
// Destructuring that takes only part of the sequence closes the iterator
const [a, b] = traced([10, 20, 30]);
// return() called after 2 value(s)
// A rest element drains the iterator, so there is no early exit
const [first, ...rest] = traced([10, 20, 30]);
// (no output)
// Spread and Array.from always read to the end
console.log([...traced([1, 2])]); // [ 1, 2 ]
console.log(Array.from(traced([1, 2]))); // [ 1, 2 ]| Consumer | Calls return() when |
|---|---|
| `for...of` | `break`, `return`, `throw`, or a labeled `break`/`continue` that leaves the loop |
| Array destructuring `[a, b] = it` | The pattern ends before the iterator is done |
| Array destructuring with rest `[a, ...r]` | Never, because rest drains the iterator |
| Spread `[...it]`, `Array.from(it)` | Only if the code that consumes it throws (for example, an `Array.from` mapping function) |
| `new Map(it)`, `new Set(it)`, `Promise.all(it)` | Only if processing an entry throws |
| Manual `it.next()` calls | Never. You must call `it.return()` yourself |
The last row matters. If you drive an iterator by hand and stop early, nothing closes it for you. Call it.return?.() yourself, ideally in a finally block.
When return() is not called
JavaScript skips IteratorClose in some cases, and these surprise people.
- The iterator finished on its own. After
done: true, the iterator is assumed to have cleaned up already. next()itself threw, or returned a non-object. The consumer treats the iterator as broken and does not call back into it.- The method doesn't exist.
return()is optional, so a missing one is not an error.
The third case has a visible effect on arrays. Array iterators have no return() method, so breaking out of a loop over an array iterator leaves it usable:
const it = [1, 2, 3, 4][Symbol.iterator]();
for (const x of it) {
if (x === 2) break;
}
for (const x of it) {
console.log(x); // 3, then 4
}Run the same code over traced([1, 2, 3, 4]) and the second loop prints nothing, because return() marked the iterator finished. Generator objects, covered in the next chapters, also have a return() method, so they act like traced here: one break closes them for good.
Rules for writing return()
A correct return() follows a few conventions.
- Release resources and mark the iterator finished. Every later
next()call should return{ value: undefined, done: true }. - Return an object. On a normal early exit (
breakorreturn), the consumer checks the result. A non-object result throws aTypeError. - Make it safe to call twice. Manual callers may close an iterator that has already closed itself.
The second rule is easy to break by accident:
const bad = {
[Symbol.iterator]() { return this; },
next() { return { value: 1, done: false }; },
return() { console.log('closing'); } // returns undefined
};
try {
for (const x of bad) break;
} catch (e) {
console.log(e instanceof TypeError); // true
}
// closing
// trueWhen the loop is leaving because of an exception, the rules change. The consumer still calls return(), but it ignores both its result and any error it throws, and the original exception keeps propagating. Cleanup code should never hide the error that caused the early exit.
A resource-holding iterator
Here is the pattern applied to a simulated resource:
function openRecords(records) {
console.log('open connection');
let i = 0;
let closed = false;
function close() {
if (!closed) {
closed = true;
console.log('close connection');
}
}
return {
[Symbol.iterator]() {
return this;
},
next() {
if (!closed && i < records.length) {
return { value: records[i++], done: false };
}
close(); // natural end: clean up here too
return { value: undefined, done: true };
},
return() {
close(); // early exit
return { value: undefined, done: true };
}
};
}
for (const r of openRecords(['r1', 'r2', 'r3'])) {
console.log(r);
if (r === 'r2') break;
}
// open connection
// r1
// r2
// close connectionCleanup lives in one idempotent close() function, which is called from both exit paths: natural completion in next() and early exit in return(). Writing this by hand is tedious. A later chapter shows how generators get the same result from a try...finally block.
Exercise
Given the traced() function from this chapter, what does this code log, and why? const [x] = traced(['a', 'b']); const [y, ...z] = traced(['a', 'b']);
Show answer
It logs "return() called after 1 value(s)" once. The first destructuring takes one value and leaves the iterator unfinished, so it calls return(). The second uses a rest element, which reads until done: true, so return() is not needed and not called.
Exercise
A loop body throws an Error, and the iterator's return() method also throws a different error. Which error reaches the surrounding catch block?
Show answer
The original error from the loop body. When the early exit is caused by an exception, the consumer calls return() but ignores its result and anything it throws, so the first exception keeps propagating.
Exercise
You call it.next() by hand three times on an iterator over a database cursor and then stop. Is return() called automatically? What should you write?
Show answer
No. Only language constructs such as for...of and destructuring call return(). Close it yourself, for example: try { it.next(); it.next(); it.next(); } finally { it.return?.(); }