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.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

Visual Explanation — How break & continue Alter Loop Flow

Normal Loop FlowWith break / continueStart LoopCheck ConditiontrueExecute BodyUpdate (i++)repeatfalseAfter LoopStart LoopCheck ConditionExecute Bodyif (...) continue;skip to nextif (...) break;exit loopAfter Loopcontinue — skips to next iterationbreak — exits loop entirely
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.

SECTION 4

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(leti=0;i<array.length;i++)if(array[i]===target)//foundit!break;//←exitstheloopimmediatelyfor (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(leti=0;i<array.length;i++)if(array[i]<0)continue;//←skipnegativenumbers//processonlynon−negativenumbersherefor (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.

SECTION 5

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.

When to Use break vs continuebreak"I found what I need — stop looping."🔍 Search & FindFind the first match in an arraye.g., find a username in a list✅ ValidationStop checking once a rule failse.g., password strength checker🎮 Game LoopsEnd the loop when a condition is mete.g., player runs out of lives⚡ PerformanceAvoid unnecessary iterationse.g., stop once limit reachedcontinue"Skip this one — move to the next."🚫 FilteringSkip items that don't meet criteriae.g., ignore empty strings🧹 Data CleaningSkip null/undefined valuese.g., process only valid entries🔢 Selective ProcessingProcess only even/odd numberse.g., skip every other item📐 Guard ClausesSkip edge cases early in loope.g., avoid division by zero
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.

SECTION 6

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. 1

    Step 1 — Set Up the Data

    Define 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. 2

    Step 2 — Use break to Find the First Failing Score

    Loop 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. 3

    Step 3 — Use continue to Sum Only Passing Scores

    Loop 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. 4

    Step 4 — Compute the Average

    const 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.

SECTION 7

break vs continue — Side-by-Side Comparison

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

Comprehensive comparison of break and continue keywords

✦

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.

SECTION 8

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.

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

Mapping loop patterns to modern JavaScript array methods

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.

SECTION 9

Practice Problems

Question 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.
Show answer
The key difference is that break terminates the entire loop, while continue only skips the remaining code in the current iteration and moves to the next one. The console.log("hello") placed immediately after continue will never execute for that iteration because continue causes JavaScript to jump back to the loop's update/condition check, skipping all subsequent statements in the loop body. The log statement is considered "unreachable code" for that specific iteration.

Question 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); }
Show answer
The output is: 1, 2, 3. The loop starts with i = 1 and prints it. Then i = 2 and i = 3 are printed. When i reaches 4, the condition i === 4 is true, so break executes and the loop exits immediately. The values 4, 5, and 6 are never printed because the loop has already terminated. The console.log(i) line is never reached when i is 4 because break comes first.

Question 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);
Show answer
The output is 30. The loop iterates through the entire array. When it encounters -3 (index 1), -1 (index 3), and 0 (index 5), the condition nums[i] <= 0 is true, so continue skips the addition step for those values. Only positive numbers are added: 10 + 7 + 5 + 8 = 30. Notice that continue did not stop the loop — it processed all 7 elements but only accumulated the ones that passed the guard condition.

Question 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.
Show answer
Here is a correct solution: const users = ["alice", "bob", "", "charlie", null, "dana"]; for (let i = 0; i < users.length; i++) { if (!users[i]) { continue; } console.log(users[i]); if (users[i] === "charlie") { break; } } This logs "alice", "bob", and "charlie". The empty string at index 2 is falsy, so continue skips it. "charlie" is logged first, then break stops the loop. The null at index 4 and "dana" at index 5 are never reached.

Question 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++; }
Show answer
This code has a critical bug: it creates an infinite loop. When i starts at 0, the condition i % 2 === 0 is true, so continue fires. However, i++ is below the continue statement, so it never executes — i stays at 0 forever. The fix is to increment i before the continue check. A corrected version: let i = 0; while (i < 10) { i++; if (i % 2 === 0) { continue; } console.log(i); } This prints 1, 3, 5, 7, 9. Alternatively, switching to a for loop avoids this trap entirely because the update expression runs automatically after each iteration.

SUMMARY

Lesson Summary

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