JAVASCRIPT • CONTROL FLOW

Break & Continue — Use break and continue appropriately

Master the two keywords that let you control exactly when and how your loops execute.

Historical Context & Motivation

Loops are one of the most powerful tools in programming — they let you repeat work without rewriting code. But what happens when you need to stop a loop early because you've found what you're looking for, or skip over certain items that don't meet your criteria? Without special keywords, you'd need clunky workarounds involving extra variables and nested if statements. The break and continue statements solve exactly this problem.

1964
BASIC Introduces GOTO
Early languages used GOTO statements to jump around in code — powerful but chaotic. Programs became tangled "spaghetti code" that was nearly impossible to debug.
1972
C Language Formalizes break & continue
Dennis Ritchie's C language introduced break and continue as structured alternatives to GOTO, keeping control flow predictable inside loops.
1995
JavaScript Adopts C-Style Control Flow
Brendan Eich designed JavaScript with C-style syntax, inheriting break and continue along with for, while, and switch statements.
2015
ES6 Adds for...of Loops
ECMAScript 2015 introduced for...of loops for iterating over arrays and other iterables, and break / continue work inside them just as they do in traditional loops.

The core question these keywords address is straightforward: how can a programmer exit or skip iterations in a clean, readable way — without resorting to flags, redundant conditions, or tangled logic? Understanding when to use break versus continue is a fundamental skill that makes your code both more efficient and easier to read.

Core Principles & Definitions

Before diving into examples, let's nail down exactly what each keyword does. Both break and continue are jump statements — they alter the normal top-to-bottom flow of a loop. However, they do very different things.

1

break — Exit the Loop Entirely

When JavaScript encounters break, it immediately stops the loop and jumps to the first line of code after the loop. No more iterations run.
2

continue — Skip to the Next Iteration

When JavaScript encounters continue, it skips the rest of the code inside the loop body for the current iteration, then moves on to the next iteration of the loop.
3

Scope — Loops & Switch Only

Both keywords can only be used inside loops (for, while, do...while). Additionally, break works inside switch statements.
4

Labels — Named Targets for Nested Loops

JavaScript supports labeled statements so that break or continue can target an outer loop when you have loops inside loops.
✦ KEY TAKEAWAY
Think of a loop like a playlist on repeat. break is like pressing the stop button — the music ends completely. continue is like pressing the skip button — you jump to the next song, but the playlist keeps playing.

Visual Explanation — How break & continue Alter Loop Flow

The left side shows a normal loop flow: check condition → execute body → update → repeat. The right side shows how continue jumps back to the condition check (skipping remaining body code), while break exits the loop completely and resumes after it.

Notice the key difference in the diagram. When continue fires, the loop doesn't end — it circles back and tries the next iteration. Any code below the continue statement in that iteration is simply never reached. When break fires, the loop is done completely. No more iterations are attempted, and execution resumes with whatever code follows the loop.

How break & continue Work Under the Hood

break in a for Loop

Consider a for loop that searches an array for a specific value. Without break, the loop would check every element even after finding the target — wasting processing time. With break, the loop stops the instant a match is found. Here is a concrete pattern:

BREAK PATTERN
for (let i = 0; i < array.length; i++) { if (array[i] === target) { // found it! break; // ← exits the loop immediately } }
i = loop counter, array = the data being searched, target = the value we want. After break, i retains the index where the target was found.

continue in a for Loop

Now consider filtering: you want to process only certain items and skip the rest. The continue statement lets you cleanly bypass unwanted items without nesting your entire loop body inside an if block.

CONTINUE PATTERN
for (let i = 0; i < array.length; i++) { if (array[i] < 0) { continue; // ← skip negative numbers } // process only non-negative numbers here }
When array[i] is negative, continue jumps straight to i++ and then the condition check. The processing code below is skipped for that iteration.

Behavior Differences: for vs. while

There's a subtle but important difference when using continue inside a while loop versus a for loop. In a for loop, the update expression (like i++) always runs after continue. In a while loop, if the counter increment is below the continue statement, it gets skipped — potentially creating an infinite loop.

⚠ ⚠ Infinite Loop Danger
When using continue in a while loop, always make sure the loop variable is updated before the continue statement, or the loop may run forever.

Common Patterns & Use Cases

Knowing the syntax is only half the battle. The real skill is recognizing when to reach for break or continue. Below is a classification of the most common patterns you'll encounter.

This reference chart groups common use cases for break (left, blue border) and continue (right, cyan border). Reach for break when you want to stop; reach for continue when you want to skip.

Labeled Statements for Nested Loops

When you have a loop inside another loop, break and continue only affect the innermost loop by default. If you need to break out of the outer loop from inside the inner one, you can use a label. A label is just a name followed by a colon placed before the loop, like outerLoop:. Then you write break outerLoop; to exit the labeled loop. Labels are rarely needed, but they're invaluable when searching through two-dimensional data like grids or tables.

Worked Example — Finding and Filtering in Arrays

Let's walk through a realistic scenario step by step. Imagine you have an array of student scores, and you need to (1) find the first failing score (below 60) and report it, and (2) calculate the average of only the passing scores.

Finding & Filtering Student Scores
1
Step 1 — Set Up the DataDefine the array of scores and the variables we need: const scores = [88, 72, 55, 91, 43, 67, 78]; let firstFail = -1; // will store the first failing score let passingSum = 0; let passingCount = 0;
2
Step 2 — Use break to Find the First Failing ScoreLoop through scores and stop at the first one below 60: for (let i = 0; i < scores.length; i++) { if (scores[i] < 60) { firstFail = scores[i]; break; // ← stop searching } }
firstFail = 55 (the loop checked indices 0, 1, and 2, then stopped — it never looked at indices 3–6)
3
Step 3 — Use continue to Sum Only Passing ScoresLoop through all scores, but skip any score below 60: for (let i = 0; i < scores.length; i++) { if (scores[i] < 60) { continue; // ← skip this score } passingSum += scores[i]; passingCount++; }
Passing scores: 88 + 72 + 91 + 67 + 78 = 396 across 5 students (55 and 43 were skipped)
4
Step 4 — Compute the Averageconst avg = passingSum / passingCount; console.log(`First fail: ${firstFail}`); // 55 console.log(`Passing avg: ${avg}`); // 79.2
Average of passing scores = 396 ÷ 5 = 79.2

Notice how clean the code is. The break in Step 2 saved us from checking four unnecessary elements. The continue in Step 3 kept the main logic (adding scores) at the top level of the loop body, avoiding a deeply nested if block. Both improve readability and efficiency.

break vs continue — Side-by-Side Comparison

Comprehensive comparison of break and continue keywords
Featurebreakcontinue
EffectExits the loop entirelySkips to the next iteration
Code after it runs?Code after the loop runs; code inside the loop does notRemaining code in current iteration is skipped; next iteration starts
Works in for loop?YesYes
Works in while loop?YesYes (but beware of infinite loops)
Works in forEach?No — use return or for...of insteadNo — use return to skip in forEach
Works in switch?Yes (prevents fall-through)No
Supports labels?YesYes
Typical useFinding first match, early terminationFiltering, skipping invalid data
✦ KEY TAKEAWAY
A common mistake is trying to use break or continue inside a .forEach() callback. This will throw a SyntaxError because .forEach() uses a callback function, not a traditional loop. If you need break/continue behavior, switch to a for...of loop instead.

Connection to Advanced Patterns

As you advance in JavaScript, you'll encounter functional programming methods like .find(), .filter(), and .some() that handle many of the same tasks as break and continue — but in a more declarative style. Understanding the imperative approach with loops first gives you a solid foundation for appreciating why these higher-level methods exist.

Mapping loop patterns to modern JavaScript array methods
Loop + break/continueArray Method EquivalentWhen to Prefer the Loop
for...break to find first matcharray.find()When you need the index (use loop) or want to perform side effects during search
for...continue to skip itemsarray.filter()When you need to mutate original data in place or combine filtering with other operations
for...break to test a conditionarray.some() / array.every()When you need to track state or perform complex checks across iterations
Nested loops with labeled breakNo direct equivalentAlways — array methods don't support breaking out of nested iterations

In professional codebases, developers often prefer array methods for simple filtering and searching because they're more concise. However, loops with break and continue remain essential for performance-critical code, complex multi-step processing, and situations where you need fine-grained control over execution. Mastering both approaches makes you a more versatile programmer.

Practice Problems

PROBLEM 1 — CONCEPTUAL
What is the key difference between break and continue? If you place a console.log("hello") on the line immediately after a continue statement inside a loop, will it ever execute for that iteration? Explain why or why not.
PROBLEM 2 — BASIC CALCULATION
Trace through the following code and determine what values are printed to the console: for (let i = 1; i <= 6; i++) { if (i === 4) { break; } console.log(i); }
PROBLEM 3 — INTERMEDIATE
What does this code print, and why? const nums = [10, -3, 7, -1, 5, 0, 8]; let total = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] <= 0) { continue; } total += nums[i]; } console.log(total);
PROBLEM 4 — APPLIED
You are building a simple login system. You have an array of usernames: ["alice", "bob", "", "charlie", null, "dana"]. Write a for loop that uses continue to skip empty strings and null values, and uses break to stop processing as soon as it finds the username "charlie". Log each valid username it processes.
PROBLEM 5 — CRITICAL THINKING
A classmate writes this code and says it will print all odd numbers from 1 to 10. Is this correct? If not, explain the bug and fix it. let i = 0; while (i < 10) { if (i % 2 === 0) { continue; } console.log(i); i++; }

Lesson Summary

The break statement exits a loop entirely, jumping to the first line of code after the loop. It's ideal for search operations where you stop once you find what you need, and for early termination when continuing would waste processing time. The continue statement skips the rest of the current iteration and moves to the next one. Use it for filtering and data cleaning — bypassing invalid or unwanted values while the loop keeps running.

Both keywords only work inside loop constructs (for, while, do...while, for...of, for...in) — not inside .forEach() callbacks. Watch out for the infinite loop trap when using continue in while loops — always update your counter before the continue. For nested loops, labeled statements let you target a specific outer loop. As you grow as a developer, you'll learn when to replace these patterns with array methods like .find() and .filter(), but the loop-based approach remains a fundamental skill every programmer must master.

Varsity Tutors • JavaScript • Break & Continue — Use break and continue appropriately