JAVASCRIPT Tutorial

Break & Continue

Introduction

Break and Continue are control statements used in loops to modify the flow of execution. Understanding their functionality is crucial for effective looping.

Loop Control

Loops are used to iterate over collections or execute a block of code multiple times. Break and Continue provide control over this iteration.

Break Statement

  • Immediately exits the loop, regardless of the iteration count.
  • The program flow continues after the loop.

Continue Statement

  • Skips the current iteration of the loop and moves to the next one.
  • The program flow continues within the loop.

Practical Steps for Using Break and Continue

  1. Identify the loop that needs to be modified.
  2. Decide whether to exit the loop (Break) or skip the current iteration (Continue).
  3. Place the Break or Continue statement at the appropriate point in the loop body.
  4. Test and ensure the desired behavior is achieved.

Example in JavaScript

const numbers = [1, 2, 3, 4, 5];

// Using Break to exit the loop early
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 3) {
    break; // Exit the loop when the value 3 is found
  }
  console.log(numbers[i]); // Log each number
}

// Using Continue to skip the current iteration
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    continue; // Skip the even numbers
  }
  console.log(numbers[i]); // Log only the odd numbers
}

Remember:

  • Break exits the loop, while Continue skips the current iteration.
  • Use these statements sparingly to maintain code clarity and avoid excessive looping logic.