Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Break Continue
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Break and Continue Statements

Controlling loop execution flow

Sometimes you need more control over your loops—you might want to exit early when you find what you're looking for, or skip certain iterations based on conditions. The break and continue statements give you precise control over loop execution. Let's master these essential loop control tools!

The Break Statement

The break statement immediately exits the loop, stopping all further iterations. Control moves to the code after the loop.

Basic Break Syntax

JAVASCRIPT
for (let i = 0; i < 10; i++) {
  if (condition) {
    break;  // Exit loop immediately
  }
  // More code
}
// Continue here after break

// Example: Stop at 5
for (let i = 0; i < 10; i++) {
  console.log(i);
  if (i === 5) {
    break;  // Exit when i is 5
  }
}
console.log("Loop ended");

// Output:
// 0, 1, 2, 3, 4, 5
// Loop ended

What happens with break:

  1. Loop is executing normally
  2. break statement is encountered
  3. Loop immediately terminates
  4. Code after the loop executes
  5. No more iterations happen

When to Use Break

JAVASCRIPT
// 1. Search - stop when found
let numbers = [5, 10, 15, 20, 25, 30];
let target = 20;
let found = false;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === target) {
    found = true;
    console.log("Found at index:", i);
    break;  // No need to continue searching
  }
}
console.log("Search complete. Found:", found);

// 2. Validation - stop at first error
let userData = ["John", "john@test.com", "", "123"];
let isValid = true;

for (let field of userData) {
  if (!field || field.trim() === "") {
    isValid = false;
    console.log("Invalid data found");
    break;  // Stop checking once error found
  }
}

// 3. Performance - limit iterations
let count = 0;
let maxIterations = 5;

for (let i = 0; i < 1000; i++) {
  count++;
  if (count >= maxIterations) {
    console.log("Reached maximum iterations");
    break;
  }
}

// 4. User interruption
let keepGoing = true;
for (let i = 0; i < 100; i++) {
  console.log("Processing:", i);
  
  // Simulate user stop
  if (i > 5) {
    keepGoing = false;
  }
  
  if (!keepGoing) {
    console.log("User stopped the process");
    break;
  }
}

The Continue Statement

The continue statement skips the rest of the current iteration and immediately starts the next iteration.

Basic Continue Syntax

JAVASCRIPT
for (let i = 0; i < 10; i++) {
  if (condition) {
    continue;  // Skip rest of this iteration
  }
  // This code is skipped if continue executes
}

// Example: Skip even numbers
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(i);  // Only odd numbers reach here
}

// Output: 1, 3, 5, 7, 9

What happens with continue:

  1. Loop iteration is executing
  2. continue statement is encountered
  3. Rest of current iteration is skipped
  4. Loop immediately starts next iteration
  5. Loop continues until condition is false

When to Use Continue

JAVASCRIPT
// 1. Filter/Skip unwanted values
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let num of numbers) {
  if (num % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(num);  // Process only odd numbers
}
// Output: 1, 3, 5, 7, 9

// 2. Skip empty/invalid data
let userInputs = ["John", "", "Jane", null, "Bob", undefined];

for (let input of userInputs) {
  if (!input || input.trim() === "") {
    continue;  // Skip invalid entries
  }
  console.log("Valid input:", input);
}
// Output: "Valid input: John", "Valid input: Jane", "Valid input: Bob"

// 3. Process only specific items
let products = [
  { name: "Laptop", category: "electronics", price: 1000 },
  { name: "Shirt", category: "clothing", price: 30 },
  { name: "Phone", category: "electronics", price: 800 },
  { name: "Pants", category: "clothing", price: 50 }
];

for (let product of products) {
  if (product.category !== "electronics") {
    continue;  // Skip non-electronics
  }
  console.log(`${product.name}: $${product.price}`);
}
// Output: "Laptop: $1000", "Phone: $800"

// 4. Skip certain conditions
for (let i = 1; i <= 10; i++) {
  if (i % 3 === 0) {
    continue;  // Skip multiples of 3
  }
  console.log(i);
}
// Output: 1, 2, 4, 5, 7, 8, 10

Break vs Continue

Different behaviors for loop control

Break (Exit Loop)

// Break: Exit entire loop
console.log("=== With Break ===");
for (let i = 0; i < 10; i++) {
  console.log(i);
  if (i === 5) {
    break;  // Stop loop
  }
}
console.log("Loop ended");

// Output:
// 0, 1, 2, 3, 4, 5
// Loop ended
// (Loop stops at 5)
Output:
Not run yet...

Continue (Skip Iteration)

// Continue: Skip iteration
console.log("=== With Continue ===");
for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue;  // Skip 5
  }
  console.log(i);
}
console.log("Loop ended");

// Output:
// 0, 1, 2, 3, 4, 6, 7, 8, 9
// Loop ended
// (Skips 5, continues)
Output:
Not run yet...

Visual Comparison

JAVASCRIPT
// Search with break vs continue
let numbers = [5, 10, 15, 20, 25];

// Break: Stop when found
console.log("=== Break Example ===");
for (let num of numbers) {
  console.log("Checking:", num);
  if (num === 15) {
    console.log("Found! Stopping search.");
    break;
  }
}
// Output:
// Checking: 5
// Checking: 10
// Checking: 15
// Found! Stopping search.

// Continue: Skip and keep going
console.log("\n=== Continue Example ===");
for (let num of numbers) {
  if (num === 15) {
    console.log("Skipping:", num);
    continue;
  }
  console.log("Processing:", num);
}
// Output:
// Processing: 5
// Processing: 10
// Skipping: 15
// Processing: 20
// Processing: 25

Break and Continue with Different Loops

With For Loops

JAVASCRIPT
// Break in for loop
for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);  // 0, 1, 2
}

// Continue in for loop
for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);  // 0, 1, 3, 4
}

With While Loops

JAVASCRIPT
// Break in while loop
let count = 0;
while (count < 10) {
  console.log(count);
  count++;
  if (count === 5) {
    break;  // Exit when count is 5
  }
}
// Output: 0, 1, 2, 3, 4

// Continue in while loop
count = 0;
while (count < 10) {
  count++;
  if (count % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(count);
}
// Output: 1, 3, 5, 7, 9

With For...of Loops

JAVASCRIPT
let fruits = ["apple", "banana", "orange", "grape", "mango"];

// Break in for...of
for (let fruit of fruits) {
  console.log(fruit);
  if (fruit === "orange") {
    break;
  }
}
// Output: apple, banana, orange

// Continue in for...of
for (let fruit of fruits) {
  if (fruit.length <= 5) {
    continue;  // Skip short names
  }
  console.log(fruit);
}
// Output: banana, orange

With For...in Loops

JAVASCRIPT
let user = {
  name: "John",
  age: 30,
  email: "john@test.com",
  password: "secret",
  city: "NYC"
};

// Break in for...in
for (let key in user) {
  console.log(`${key}: ${user[key]}`);
  if (key === "email") {
    break;  // Stop after email
  }
}

// Continue in for...in
for (let key in user) {
  if (key === "password") {
    continue;  // Skip password
  }
  console.log(`${key}: ${user[key]}`);
}
// Shows all except password

Break and Continue in Nested Loops

In nested loops, break and continue only affect the innermost loop they're in.

Break in Nested Loops

JAVASCRIPT
// Break only exits inner loop
for (let i = 0; i < 3; i++) {
  console.log("Outer:", i);
  
  for (let j = 0; j < 3; j++) {
    console.log("  Inner:", j);
    if (j === 1) {
      break;  // Only exits inner loop
    }
  }
}

// Output:
// Outer: 0
//   Inner: 0
//   Inner: 1
// Outer: 1
//   Inner: 0
//   Inner: 1
// Outer: 2
//   Inner: 0
//   Inner: 1

// To exit outer loop, use a flag
let shouldStop = false;

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(`[${i}][${j}]`);
    if (i === 1 && j === 1) {
      shouldStop = true;
      break;
    }
  }
  if (shouldStop) break;
}
console.log("Both loops stopped");

Continue in Nested Loops

JAVASCRIPT
// Continue only skips current iteration of inner loop
for (let i = 0; i < 3; i++) {
  console.log("Outer:", i);
  
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue;  // Skip j=1 in inner loop
    }
    console.log("  Inner:", j);
  }
}

// Output:
// Outer: 0
//   Inner: 0
//   Inner: 2
// Outer: 1
//   Inner: 0
//   Inner: 2
// Outer: 2
//   Inner: 0
//   Inner: 2

Labeled Statements (Advanced)

JAVASCRIPT
// Use labels to break/continue outer loops
outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(`[${i}][${j}]`);
    if (i === 1 && j === 1) {
      break outerLoop;  // Break outer loop
    }
  }
}
console.log("Outer loop exited");

// Output:
// [0][0]
// [0][1]
// [0][2]
// [1][0]
// [1][1]
// Outer loop exited

// Continue with label
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue outer;  // Skip to next outer iteration
    }
    console.log(`[${i}][${j}]`);
  }
}

// Output:
// [0][0]
// [1][0]
// [2][0]

Labeled statements: While powerful, labeled break and continue can make code harder to read. Use them sparingly and consider refactoring into functions instead.

Practical Patterns

Pattern 1: Early Exit (Break)

JAVASCRIPT
// Find first matching item
function findUser(users, id) {
  for (let user of users) {
    if (user.id === id) {
      return user;  // Found it, exit immediately
    }
  }
  return null;  // Not found
}

// Check if all conditions met
function validateAll(items) {
  for (let item of items) {
    if (!isValid(item)) {
      return false;  // One invalid, stop checking
    }
  }
  return true;  // All valid
}

function isValid(item) {
  return item && item.length > 0;
}

// Process until quota reached
function processUntilQuota(items, maxItems) {
  let processed = 0;
  let results = [];
  
  for (let item of items) {
    results.push(processItem(item));
    processed++;
    
    if (processed >= maxItems) {
      break;  // Reached quota
    }
  }
  
  return results;
}

function processItem(item) {
  return item.toUpperCase();
}

Pattern 2: Filtering (Continue)

JAVASCRIPT
// Process only valid items
function processValidItems(items) {
  let results = [];
  
  for (let item of items) {
    // Skip invalid
    if (!item || item === null) {
      continue;
    }
    
    // Skip duplicates
    if (results.includes(item)) {
      continue;
    }
    
    // Process valid unique items
    results.push(item);
  }
  
  return results;
}

// Calculate sum, skip negative
function sumPositive(numbers) {
  let sum = 0;
  
  for (let num of numbers) {
    if (num < 0) {
      continue;  // Skip negative
    }
    sum += num;
  }
  
  return sum;
}

console.log(sumPositive([5, -3, 10, -1, 8]));  // 23

// Build filtered array
function filterAdults(people) {
  let adults = [];
  
  for (let person of people) {
    if (person.age < 18) {
      continue;  // Skip minors
    }
    adults.push(person);
  }
  
  return adults;
}

Pattern 3: Search with Early Exit

JAVASCRIPT
// Find first occurrence
function findFirst(array, condition) {
  for (let i = 0; i < array.length; i++) {
    if (condition(array[i])) {
      return { found: true, index: i, value: array[i] };
    }
  }
  return { found: false };
}

let numbers = [5, 10, 15, 20, 25];
let result = findFirst(numbers, num => num > 12);
console.log(result);  // { found: true, index: 2, value: 15 }

// Check if any element satisfies condition
function hasElement(array, condition) {
  for (let item of array) {
    if (condition(item)) {
      return true;  // Found one, stop searching
    }
  }
  return false;
}

let hasLargeNumber = hasElement(numbers, num => num > 20);
console.log(hasLargeNumber);  // true

// Get first N valid items
function getFirstN(array, n, condition) {
  let results = [];
  
  for (let item of array) {
    if (!condition(item)) {
      continue;  // Skip invalid
    }
    
    results.push(item);
    
    if (results.length >= n) {
      break;  // Got enough
    }
  }
  
  return results;
}

let firstThreeEvens = getFirstN(
  [1, 2, 3, 4, 5, 6, 7, 8],
  3,
  num => num % 2 === 0
);
console.log(firstThreeEvens);  // [2, 4, 6]

Practical Examples

Example 1: Login Validator with Retry Limit

JAVASCRIPT
function attemptLogin(username, password, maxAttempts = 3) {
  let attempts = 0;
  let isAuthenticated = false;
  let correctPassword = "secret123";
  
  while (attempts < maxAttempts) {
    attempts++;
    console.log(`Attempt ${attempts} of ${maxAttempts}`);
    
    // Check username
    if (!username || username.trim() === "") {
      console.log("Username required");
      continue;  // Skip to next attempt
    }
    
    // Check password
    if (password === correctPassword) {
      isAuthenticated = true;
      console.log("✓ Login successful!");
      break;  // Stop trying
    } else {
      console.log("✗ Incorrect password");
      
      // Simulate new password attempt
      password = attempts === 2 ? correctPassword : "wrong";
    }
  }
  
  if (!isAuthenticated) {
    console.log("⚠ Account locked after", maxAttempts, "failed attempts");
  }
  
  return {
    success: isAuthenticated,
    attempts: attempts
  };
}

console.log(attemptLogin("john", "wrong"));

Example 2: Data Processor with Validation

JAVASCRIPT
function processOrders(orders) {
  let processed = [];
  let skipped = [];
  let stopped = false;
  
  for (let i = 0; i < orders.length; i++) {
    let order = orders[i];
    
    // Skip invalid orders
    if (!order.id) {
      skipped.push({ order, reason: "Missing ID" });
      continue;
    }
    
    if (!order.total || order.total <= 0) {
      skipped.push({ order, reason: "Invalid total" });
      continue;
    }
    
    // Stop if critical error
    if (order.total > 10000) {
      console.log("Critical: Order too large, stopping processing");
      stopped = true;
      break;
    }
    
    // Process valid order
    processed.push({
      id: order.id,
      total: order.total,
      tax: order.total * 0.08,
      status: "processed"
    });
  }
  
  return {
    processed: processed,
    skipped: skipped,
    stopped: stopped,
    summary: {
      total: orders.length,
      processed: processed.length,
      skipped: skipped.length
    }
  };
}

let orders = [
  { id: 1, total: 50 },
  { total: 75 },           // Missing ID
  { id: 3, total: -10 },   // Invalid total
  { id: 4, total: 100 },
  { id: 5, total: 15000 }  // Too large, will stop
];

console.log(processOrders(orders));

Break and Continue Practice

Experiment with loop control statements

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • break exits the entire loop immediately
  • continue skips current iteration, continues to next
  • Use break for early exit when goal is reached
  • Use continue to skip invalid/unwanted items
  • Both work with all loop types (for, while, do-while, for...of, for...in)
  • In nested loops, they only affect the innermost loop
  • Use labeled statements to break/continue outer loops (use sparingly)
  • break improves performance by stopping unnecessary iterations
  • continue makes filtering logic cleaner and more readable
  • Can use both in same loop for complex control flow

What's Next?

Congratulations! You've completed the Loops and Iteration section. You now know how to use for loops, while loops, do-while loops, for...of, for...in, and control loop execution with break and continue. Loops are fundamental to programming—you'll use them constantly!

In the next section, we'll dive into Functions— reusable blocks of code that help you organize and structure your programs. Functions are one of the most important concepts in JavaScript, enabling you to write cleaner, more maintainable code!

💪 Practice Challenge:

Before moving on, try creating:

  1. A function that finds the first prime number in an array using break
  2. A function that sums only positive numbers using continue
  3. A nested loop that finds a specific value in a 2D array and breaks both loops
  4. A validator that stops at the first error using break
  5. A function that processes an array but skips duplicates using continue

Test Your Understanding

Question 1 / 4

What does the 'break' statement do?

Score: 0 / 0

Mastering JavaScript loop control! 🔄🛑

Previous
For...of and For...in Loops
Next
Function Declarations and Expressions

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript fundamentals. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo