JavaScript:JavaScript Break and Continue Statements in Loops
JavaScript•Loop Control

JavaScript Break and Continue Statements in Loops

break terminates the loop immediately; continue skips the remainder of the current iteration.

Syntax

if (stopCondition) break; if (skipCondition) continue;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
breakStatementExits loop completely.
continueStatementSkips current iteration and moves to next.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// break and continue Demonstration
const searchIds = [101, 102, -1, 104, 999, 106];

console.log("Processing records:");
for (const id of searchIds) {
  // Skip invalid negative IDs
  if (id < 0) {
    console.log("  [SKIPPED] Invalid ID: " + id);
    continue;
  }

  // Stop processing when sentinel ID 999 is encountered
  if (id === 999) {
    console.log("  [HALT] Sentinel ID 999 reached. Terminating.");
    break;
  }

  console.log("  Processed valid record ID: " + id);
}
Expected Output:
Processing records:
  Processed valid record ID: 101
  Processed valid record ID: 102
  [SKIPPED] Invalid ID: -1
  Processed valid record ID: 104
  [HALT] Sentinel ID 999 reached. Terminating.

How It Works: Step-by-Step

  • Lines 7-10: continue jumps over -1 without processing further.
  • Lines 13-16: break terminates loop immediately upon finding 999.

Key Concepts

  • continue skips remaining statements in the current iteration.
  • break terminates loop execution entirely.
  • Both statements can be paired with labeled loops for breaking nested structures.

Common Mistake: Using break inside forEach callback

break is a syntax error inside array callback methods like forEach. Use a for...of loop instead.

❌ Incorrect
[1, 2, 3].forEach(x => {
  if (x === 2) break; // SyntaxError: Illegal break statement
});
✅ Correct
for (const x of [1, 2, 3]) {
  if (x === 2) break; // Clean loop termination
}

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler