JavaScript Jump Statements: break, continue, Labels and return
How break and continue change the flow of loops and switch, where each one jumps, labeled statements for leaving nested loops, the break-inside-switch-inside-loop trap, why return in forEach doesn't stop it, early exit with find and some, and the rules for return.
kvi5hnuCode Sprout team member7 min readOn this page
Normally statements run in order, and loops repeat their body until the condition fails. Jump statements change that: they transfer control somewhere else immediately.
breakleaves a loop orswitch(or a labeled statement).continueskips to the next iteration of a loop.returnleaves a function, optionally with a value.throwleaves everything until an exception handler catches it (next article).
Used well, they make code shorter and flatter. Used carelessly, they make it hard to follow, so this article also covers when to reach for something else.
break
break ends the innermost enclosing loop or switch immediately. Execution continues with the statement after it:
const temperatures = [18, 21, 35, 19, 40];
let firstHot = -1;
for (let i = 0; i < temperatures.length; i++) {
if (temperatures[i] > 30) {
firstHot = i;
break; // no need to look at the rest
}
}
console.log(firstHot);
2
break in a while (true) loop is the standard way to write a loop whose exit condition is easiest to check in the middle:
while (true) {
const line = readNextLine();
if (line === null) break; // end of input
process(line);
}
break is only allowed inside a loop or switch (or a labeled statement, below). Anywhere else, it's a SyntaxError.
continue
continue ends the current iteration and moves on to the next one. Where "next" starts depends on the loop:
while: back to the condition.do/while: down to the condition at the bottom.for: to the update expression, then the condition.for...of/for...in: to the next value or key.
const orders = [{ id: 1, paid: true }, { id: 2, paid: false }, { id: 3, paid: true }];
const shipped = [];
for (const order of orders) {
if (!order.paid) continue; // skip unpaid orders
shipped.push(order.id);
}
console.log(shipped);
[ 1, 3 ]
continue works like a guard clause inside a loop (article 39): deal with the cases to skip first, and keep the main logic unnested.
Labels: break and continue for outer loops
break and continue affect only the innermost loop. To control an outer loop from inside a nested one, give the outer loop a label (an identifier followed by a colon) and name it:

const grid = [
[3, 8, 1],
[7, -2, 5],
[4, 6, 9],
];
let firstNegative = null;
rows: for (const [r, row] of grid.entries()) {
for (const [c, value] of row.entries()) {
if (value < 0) {
firstNegative = [r, c];
break rows; // leave both loops at once
}
}
}
console.log(firstNegative);
[ 1, 1 ]
Without the label, break would only end the inner loop, and the search would continue with the next row. continue label works the same way, starting the next iteration of the labeled loop:
const visited = [];
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) continue outer; // skip the rest of this row
visited.push(`${i}${j}`);
}
}
console.log(visited.join(" "));
00 10 20
Rules for labels:
- Any statement can be labeled, but only
breakandcontinueuse labels.continue labelmust name a loop;break labelcan name any enclosing statement, even a plain block. - Labels have their own namespace, so a label can share a name with a variable.
breakandcontinuecan't cross a function boundary: you can't break out of a loop from inside a callback.- No line break is allowed between
break/continueand the label, or automatic semicolon insertion ends the statement early (article 8).
Labels are rare in everyday code, and some style guides discourage them (ESLint's no-labels). For nested searches, a common alternative is to move the loops into a function and use return, which ends both loops just as well and gives the search a name.
The switch-inside-a-loop trap
Inside a switch, a plain break ends the switch, not the loop around it:
const commands = ["start", "stop", "status"];
const ran = [];
for (const cmd of commands) {
switch (cmd) {
case "stop":
break; // only leaves the switch: the loop goes on
default:
ran.push(cmd);
}
}
console.log(ran);
const ranUntilStop = [];
loop: for (const cmd of commands) {
switch (cmd) {
case "stop":
break loop; // leaves the loop
default:
ranUntilStop.push(cmd);
}
}
console.log(ranUntilStop);
[ 'start', 'status' ]
[ 'start' ]
continue inside a switch does affect the loop, because switch isn't a loop. Labeled break, a flag variable, or return from a function are the ways to stop the loop from inside a switch.
return
return expression; ends the current function and makes the call evaluate to expression. A bare return;, or reaching the end of the function, gives undefined. It's only allowed inside functions: at the top level of a script or module, it's a SyntaxError.
function firstOver(limit, values) {
for (const v of values) {
if (v > limit) return v; // also ends the loop
}
return null; // nothing found
}
console.log(firstOver(10, [4, 12, 30]), firstOver(10, []));
12 null
Remember the one ASI rule that bites here: a line break right after return ends the statement, so return followed by an object literal on the next line returns undefined (article 8). Start the value on the same line as return.
Inside a try block that has a finally, the finally code still runs after a return, break or continue (next article).
return inside forEach doesn't stop the loop
forEach calls your function once per element. return inside it only ends that call; it works like continue, not break:
const seen = [];
[1, 2, 3, 4].forEach((n) => {
if (n === 2) return; // skips 2, but forEach keeps going
seen.push(n);
});
console.log(seen);
[ 1, 3, 4 ]
break and continue aren't allowed inside the callback at all. To stop early, use for...of, or an array method that's designed to stop: find, findIndex, some and every stop as soon as they have their answer:
const checked = [];
const hasNegative = [5, -1, 8, 3].some((n) => {
checked.push(n);
return n < 0;
});
console.log(hasNegative, checked);
console.log([5, 12, 8, 130].find((n) => n > 10));
true [ 5, -1 ]
12
yield, briefly
yield is the jump statement of generator functions (function*): it pauses the function and hands a value to whoever is iterating, then resumes from the same point when the next value is requested. Part 12 covers generators; you saw one in article 42 cleaning up after a break.
Common questions
Are break and continue bad style?
No. They're often the clearest way to express "stop when found" or "skip these". What hurts readability is many jumps scattered through a long loop body. If a loop has several breaks and continues, consider extracting it into a function, or using find, filter and some.
Can I break out of a plain block?
Yes, with a label: the code below. It works, but an if statement or an early return from a small function is clearer, and it's rarely seen in real code.
check: { if (!valid) break check; process(); }
How do I stop a .map() or .reduce() halfway?
You can't, short of throwing an exception. Use a for...of loop when you need to stop early, or first narrow the data with slice/filter, or use find/some when you're searching.
Does break work in for await loops?
Yes. break, continue, return and labels work in for await...of exactly as in for...of, and breaking out lets the async iterator clean up (closing a stream, for example).
Summary
breakends the innermost loop orswitch;continuejumps to the next iteration (in aforloop, via the update).- Labels (
name:) letbreak nameandcontinue nametarget an outer loop;break namecan also leave a labeled block. - A
breakinside aswitchinside a loop only leaves theswitch. returnends the whole function, including any loops in it; don't put a line break right afterreturn.returnin aforEachcallback only skips that element; usefor...of,find,someoreveryto stop early.
Practice Questions
What does this print?
let s = "";
for (let i = 0; i < 5; i++) {
if (i === 1) continue;
if (i === 3) break;
s += i;
}
console.log(s);
Answer
"02". i = 0 is added; i = 1 is skipped by continue; i = 2 is added; at i = 3, break ends the loop.
Why might this loop never end?
let i = 0;
while (i < 5) {
if (i === 2) continue;
i++;
}
Answer
When i reaches 2, continue jumps back to the condition without running i++, so i stays 2 forever. Move the increment before the continue, or use for (let i = 0; i < 5; i++).
Rewrite this labeled search as a function using return: find the first pair [a, b] from xs and ys with a + b === 10.
Answer
function findPair(xs, ys) {
for (const a of xs) {
for (const b of ys) {
if (a + b === 10) return [a, b];
}
}
return null;
}
return exits both loops at once, with no label needed.
Inside a loop, a switch handles case "quit": break;. The loop keeps running after "quit". Give two fixes.
Answer
Label the loop and write break loopName; in that case, or put the loop in a function and return from the case. A third option is to set a flag such as running = false and test it in the loop condition.
Previous: JavaScript for...of and for...in Loops: Iterating Arrays, Strings, Maps and Object Keys
Next: JavaScript Exceptions: throw, try/catch/finally, Error Types and Error Handling Patterns

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.