Javascript Break And Continue Statements Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of JavaScript break and continue Statements

JavaScript break and continue Statements

The break Statement

The break statement is used to exit a loop prematurely. When encountered inside a loop, it terminates the loop immediately and continues with the next line of code after the loop block. This can be particularly useful when you've found the necessary information and want to stop unnecessary iterations.

Here's how the break statement works in different types of loops:

1. In for Loop:

// Display numbers from 1 to 5 but exit the loop when the number is 3
for (let i = 1; i <= 5; i++) {
    if (i === 3) { // Condition to meet 'break'
        break;
    }
    console.log(i); // Outputs: 1, 2
}

2. In while Loop:

let counter = 1;

while (counter <= 5) {
    if (counter === 3) {
        break;
    }
    console.log(counter); // Outputs: 1, 2
    counter++;
}

3. In do...while Loop:

let count = 1;

do {
    if (count === 3) {
        break;
    }
    console.log(count); // Outputs: 1, 2
    count++;
} while (count <= 5);
Key Points:
  • Immediacy: The loop terminates as soon as break is executed.
  • Label Support: You can also use break with labeled statements to exit nested loops.
  • Efficiency: Use break to avoid executing redundant iterations once a certain condition is met.

Example of using labels with break:

outerLoop: // Labeling the outer loop
for (let i = 1; i < 4; i++) {
    innerLoop: // Labeling the inner loop
    for (let j = 1; j < 4; j++) {
        if (i * j > 5) {
            break outerLoop; // Breaking out of the labeled 'outerLoop'
        }
        console.log(`i=${i}, j=${j}`);
        // Outputs: i=1, j=1 | i=1, j=2 | i=1, j=3 | i=2, j=1 | i=2, j=2
    }
}

The continue Statement

The continue statement is used to skip the current iteration of a loop and proceed to the next one without executing the code following it within the same iteration. It’s valuable for excluding certain elements or conditions during iteration without completely terminating the loop.

Here's an example using a for loop:

1. Basic Usage in for Loop:

// Display even numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
    if (i % 2 !== 0) { // Skip odd numbers
        continue;
    }
    console.log(i); // Outputs: 2, 4
}
Key Points:
  • Iteration Skipping: Only the current iteration is skipped; the loop continues with the next iteration.
  • Label Support: Similar to break, continue supports labels to skip iterations in nested loops.
  • Optimization: Utilize continue for skipping undesirable conditions rather than embedding conditional logic outside the loop structure which could lead to nested if-else blocks.

Example of using labels with continue:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement JavaScript break and continue Statements

JavaScript break Statement

The break statement is used to exit a loop or a switch statement. It stops the execution of the loop and continues with the code after the loop.

Example 1: Breaking out of a for loop

Let's create a simple for loop that prints numbers from 1 to 5, but we will use the break statement to exit the loop when it reaches the number 3.

// Initialize the loop
for (let i = 1; i <= 5; i++) {
  // Check if i is equal to 3
  if (i === 3) {
    console.log("Break at 3");
    // Exit the loop
    break;
  }
  // Print the current value of i
  console.log(i);
}

// Continue with code after the loop
console.log("Loop has ended.");

Output:

1
2
Break at 3
Loop has ended.

Explanation:

  • The loop starts at i = 1 and increments i by 1 in each iteration.
  • When i equals 3, the if condition inside the loop is true, and the break statement is executed.
  • This exits the loop immediately, and the remaining iterations are skipped.
  • The execution continues with the code after the loop, printing "Loop has ended."

JavaScript continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next iteration.

Example 2: Skipping even numbers in a for loop

Let's create a simple for loop that prints numbers from 1 to 5, but we will use the continue statement to skip even numbers.

// Initialize the loop
for (let i = 1; i <= 5; i++) {
  // Check if i is even
  if (i % 2 === 0) {
    console.log(i + " is even. Skipping...");
    // Skip the current iteration and go to the next one
    continue;
  }
  // Print the current value of i
  console.log(i);
}

// Continue with code after the loop
console.log("Loop has ended.");

Output:

1
2 is even. Skipping...
3
4 is even. Skipping...
5
Loop has ended.

Explanation:

  • The loop starts at i = 1 and increments i by 1 in each iteration.
  • In each iteration, it checks if i is even using the modulus operator (%).
  • If i is even, it prints a message and the continue statement is executed, which skips the remaining code in the current iteration and moves to the next iteration.
  • If i is odd, it simply prints the value of i.
  • The loop continues until i is greater than 5.
  • The execution continues with the code after the loop, printing "Loop has ended."

Example 3: break and continue in a while loop

Let's see how break and continue work in a while loop. We'll create a loop that prints numbers from 1 to 10, but we skip the even numbers and break the loop when it reaches 7.

// Initialize the counter
let i = 1;

// Start the while loop
while (i <= 10) {
  // Check if i is even
  if (i % 2 === 0) {
    console.log(i + " is even. Skipping...");
    // Skip the current iteration and go to the next one
    i++;
    continue;
  }
  // Check if i is 7
  if (i === 7) {
    console.log("Break at 7");
    // Exit the loop
    break;
  }
  // Print the current value of i
  console.log(i);
  // Increment the counter
  i++;
}

// Continue with code after the loop
console.log("Loop has ended.");

Output:

1
2 is even. Skipping...
3
4 is even. Skipping...
5
6 is even. Skipping...
Break at 7
Loop has ended.

Explanation:

  • The loop starts with i = 1.
  • In each iteration, it checks if i is even using the modulus operator (%).
  • If i is even, it prints a message and increments i before the continue statement is executed, which skips the rest of that iteration.
  • If i is odd, it checks if i is 7. If so, it prints a message and the break statement is executed, which exits the loop.
  • If i is neither even nor 7, it simply prints the value of i and increments i.
  • The loop continues until the break statement is executed or i becomes greater than 10.
  • The execution continues with the code after the loop, printing "Loop has ended."

Top 10 Interview Questions & Answers on JavaScript break and continue Statements

Top 10 Questions on JavaScript Break and Continue Statements

  1. What do break and continue statements do in JavaScript?

    • The break statement is used to exit from a loop (like for, while, or do...while) prematurely when a certain condition is met inside the loop.
    • The continue statement, on the other hand, skips the current iteration of a loop and proceeds directly to the next iteration without exiting the loop completely.
  2. Can you provide examples of using break and continue in for loops?

    • Using break:

      for (let i = 0; i < 10; i++) {
        if (i === 5) {
          break;  // Stops the loop when i equals 5
        }
        console.log(i);
      }
      

      In this example, numbers from 0 through 4 will be printed, but the loop stops as soon as i equals 5 because of the break.

    • Using continue:

      for (let i = 0; i < 10; i++) {
        if (i % 2 === 0) {
          continue;  // Skips even numbers
        }
        console.log(i);
      }
      

      This example will print only odd numbers between 1 and 9, as it skips all even numbers due to the continue.

  3. How does the break statement work differently inside switch cases compared to loops?

    • Inside the switch statement, break is used to exit a case block once the matched case is executed. Without break, the code will continue executing the subsequent cases until it encounters another break or the end of the switch statement.
      let fruit = 'apple';
      switch(fruit) {
        case 'banana':
          console.log('It is a banana');
          break;
        case 'apple':
          console.log('It is an apple');
          break;
        default:
          console.log('Unknown fruit');
      }
      
      In this example, the text "It is an apple" will be logged, and then the break statement will ensure that no further cases are executed.
  4. Is there a way to use both break and continue together in a loop?

    • Yes, they can work together within the same loop based on different conditions.
      for(let i = 0; i <= 10; i++) {
        if(i == 3 || i == 8){
          continue; // Skips the number 3 and 8
        }
        if(i == 6){
          break;  // Ends the loop when i equals 6
        }
        console.log("Number:", i);
      }
      
      Here, numbers 1, 2, 4, 5 are printed, then the loop is skipped entirely for 3 and 8, and it stops execution after reaching 6.
  5. What implications are there for using break and continue without proper logical reasoning?

    • Using break and continue without proper understanding can make code harder to follow logically, leading to bugs or unintended behavior. It's essential to clearly define conditions and ensure that these statements align with your overall program logic.
  6. Are break and continue applicable only to loops and switches?

    • Break is primarily used in loops and switch statements to control the flow. However, JavaScript also supports labeled break, which can be used to break out of nested loops, though it’s not commonly recommended due to code complexity.
  7. Can you explain how the break statement differs when nested in multiple loops?

    • When used in nested loops, break applies to the nearest enclosing loop unless labeled. A labeled break can be used to break out of specific named loops.
      outer: for (let i = 0; i < 5; i++) { 
        inner: for (let j = 0; j < 5; j++) { 
          if (i * j > 10) break outer; // Exits both loops
        } 
      }
      
  8. How can continue affect performance in loops?

    • Although continue can be useful, its usage might reduce performance slightly if the loop runs many times, especially if the continue logic is computationally expensive. This can vary depending on the context, so it's often better to profile performance before optimizing.
  9. Should one always use break and continue to exit loops early?

    • Not necessarily. While break and continue offer flexibility, overusing them can lead to unclear and complex code. Many developers prefer using functions that return values early if conditions aren’t met, as it can aid readability and maintainability. However, these statements can be advantageous when used judiciously.
  10. Are there any best practices or recommendations while using break and continue?

    • Yes: Clearly document where break and continue are used and why.
    • Avoid using break and continue excessively, especially in nested loops, as these can obscure the intent and make debugging more complex.
    • Prefer return statements for breaking out of functions or exiting loops based on return conditions for simplicity and clarity.
    • Use labeled break sparingly if necessary, keeping in mind that this adds complexity to the program.

You May Like This Related .NET Topic

Login to post a comment.