Sub topic 14
break, continue and Early Exit
This chapter assumes you know how for...of drives an iterator by calling next() (covered in the previous chapter). You should also be comfortable with generator functions (function*), try...finally, and plain objects that hold methods. The goal is to understand what each way of leaving or skipping part of a loop does to the iterator underneath.
The Four Ways Out
A loop body can affect the loop in four ways besides running to the end:
continueskips the rest of the current iteration and asks for the next value.breakleaves the loop completely.returnleaves the loop and the enclosing function.throw(or an uncaught error) leaves the loop and propagates up the call stack.
With a classic for loop or for...in, that is the whole story. for...of adds one more step. When the loop stops before the iterator reports done: true, the loop calls the iterator's optional return() method so the source can release whatever it holds, such as a file handle, a network stream, or a generator's finally block. This step is called iterator closing.
Watching return() Get Called
The clearest way to see iterator closing is to write an iterator by hand and log from its return() method.
function makeSource(label) {
return {
[Symbol.iterator]() {
let i = 0;
return {
next() {
return { value: i++, done: i > 5 };
},
return() {
console.log(`${label}: return() called`);
return { done: true };
}
};
}
};
}
// 1. Normal completion: return() is NOT called
for (const n of makeSource('normal')) {}
console.log('normal finished');
// 2. continue: return() is NOT called
for (const n of makeSource('continue')) {
if (n % 2 === 0) continue;
console.log('odd', n);
}
// 3. break: return() IS called
for (const n of makeSource('break')) {
if (n === 2) break;
}
// 4. return from a function: return() IS called
function findFirstOver(limit) {
for (const n of makeSource('return')) {
if (n > limit) return n;
}
}
console.log('found', findFirstOver(1));
// 5. throw: return() IS called, then the error propagates
try {
for (const n of makeSource('throw')) {
if (n === 1) throw new Error('boom');
}
} catch (err) {
console.log('caught', err.message);
}Output:
normal finished
odd 1
odd 3
break: return() called
return: return() called
found 2
throw: return() called
caught boomcontinue never closes the iterator, because the loop is still running. Natural completion doesn't close it either, because the iterator has already said it is finished and has nothing left to clean up.
| How the loop stops | `return()` called? | What happens next |
|---|---|---|
| `next()` returns `done: true` | No | Code after the loop runs |
| `continue` | No (loop continues) | `next()` is called again |
| `break` | Yes | Code after the loop runs |
| `break label` to an outer loop | Yes, for every loop exited | Code after the labelled statement runs |
| `return` | Yes | The function returns |
| `throw` in the body | Yes | The original error propagates |
| `next()` itself throws | No | The error propagates |
The last row is an edge case. If the iterator's own next() throws, the loop assumes the iterator is broken and does not try to close it.
Generators and finally
Generators implement return() for you. Calling it resumes the generator as if a return statement appeared at the paused yield, so any finally block runs. That gives you a reliable place for cleanup code:
function* readLines() {
console.log('open');
try {
yield 'line 1';
yield 'line 2';
yield 'line 3';
} finally {
console.log('close');
}
}
for (const line of readLines()) {
console.log(line);
if (line === 'line 2') break;
}
// open
// line 1
// line 2
// closeWithout break, the finally block still runs, because the generator body finishes normally after the last yield. In both cases the consumer doesn't need to remember to call any cleanup code.
function* nums() {
yield 1; yield 2; yield 3; yield 4;
}
const gen = nums();
for (const n of gen) {
if (n === 2) break;
}
for (const n of gen) {
console.log('second loop', n); // never runs
}Array Iterators Don't Close
Built-in array, string, Map and Set iterators have no return() method. Breaking out of them closes nothing, so an iterator you hold on to keeps its position:
const it = [1, 2, 3, 4].values();
for (const x of it) {
if (x === 2) break;
}
for (const x of it) {
console.log(x);
}
// 3
// 4This works because an array iterator is itself iterable (its Symbol.iterator returns itself). Generators behave differently, as the previous section showed. If your code needs to "consume a few items, then hand the rest elsewhere", know which kind of iterator you have. With a generator, a break throws the rest of its values away.
Labelled break Across Nested Loops
A plain break exits only the innermost loop. To get out of several loops at once, put a label on the outer loop and break to it. Each for...of loop that is exited gets its iterator closed, innermost first:
function* tracked(name, items) {
try {
yield* items;
} finally {
console.log(`${name} closed`);
}
}
outer: for (const row of tracked('rows', [[1, 2], [3, 4]])) {
for (const cell of tracked('cells', row)) {
if (cell === 2) break outer;
console.log(cell);
}
}
// 1
// cells closed
// rows closedcontinue outer also works. It closes the inner iterator, because that loop is being exited, and then asks the outer iterator for its next value. The outer iterator stays open.
Early Exit Is Impossible in forEach
Array.prototype.forEach calls a callback for each element. Inside that callback, break and continue are syntax errors. return only ends the current callback call, so it behaves like continue. The only way to stop forEach early is to throw, which is clumsy.
const items = [5, 8, 12, 3];
// return acts like continue here; all four are visited
items.forEach(n => {
if (n > 10) return;
console.log('forEach', n);
});
// for...of can really stop
for (const n of items) {
if (n > 10) break;
console.log('for...of', n);
}When you need to stop early, use for...of, or a method built for it: find, some, every, or findIndex.
Common Errors
- Expecting
continueto trigger cleanup. It doesn't. Cleanup runs only when the loop stops for good. - Reusing a generator after
break. The second loop silently does nothing. - Returning a non-object from a custom
return(). Afterbreakorreturn, the loop checks the result and throws aTypeErrorif it is not an object. When the loop is exiting because of athrow, the original error wins and the result ofreturn()is ignored. - Using
returninsideforEachas if it werebreak. The loop keeps going. - Putting cleanup after a
yieldinstead of infinally. Code placed after the lastyieldnever runs if the consumer breaks early.
Exercise
A generator has console.log('done') placed after its final yield, with no try/finally. A for...of loop over it breaks on the first value. Is 'done' printed? What change guarantees it is printed?
Show answer
No. break calls the generator's return(), which ends it at the paused yield, so code after that yield never runs. Wrap the yields in try { ... } finally { console.log('done'); } so the message prints on normal completion, break, return, or a throw in the loop body.
Exercise
Given const it = new Set(['a', 'b', 'c']).values();, a loop for (const v of it) { if (v === 'a') break; } runs, and then console.log([...it]); runs. What is printed, and would the answer change if it were a generator yielding the same three values?
Show answer
It prints ['b', 'c'], because Set iterators have no return() method and keep their position after break. With a generator, break would call return() and close it, so the spread would produce [].
Exercise
In a labelled nested loop outer: for (const a of genA()) { for (const b of genB()) { if (cond) continue outer; } }, which iterators are closed when continue outer runs?
Show answer
Only the inner genB() iterator is closed, because its loop is exited. The outer genA() iterator stays open and the outer loop calls its next() for the following value.