JavaScript break Statement

In this chapter, we will learn about the JavaScript break statement. The break statement is used to terminate the execution of a loop, switch, or labeled statement prematurely. We will cover:

  • What is the break Statement?
  • Syntax
  • Using the break Statement in Loops
  • Using the break Statement in switch Statements
  • Breaking Out of Nested Loops
  • Simple Programs using the break Statement

What is the break Statement?

The break statement is used to exit a loop or switch statement before it has completed all its iterations or cases. It immediately transfers the control to the statement following the loop or switch.

Syntax

break;

Using the break Statement in Loops

Example

// Initialize the counter variable
let i = 0;

// Loop until the condition is false
while (i < 10) {
  // Check if the counter is equal to 5
  if (i === 5) {
    // Exit the loop when the counter is 5
    break;
  }
  // Print the current value of the counter
  console.log(i);
  // Increment the counter
  i++;
}

Output:

0
1
2
3
4

In the example above, the break statement exits the loop when the counter i reaches 5.

Using the break Statement in switch Statements

Example

// Define the day of the week
let day = 2;

// Determine the name of the day
switch (day) {
  case 1:
    // Case for Sunday
    console.log("Sunday");
    // Exit the switch statement
    break;
  case 2:
    // Case for Monday
    console.log("Monday");
    // Exit the switch statement
    break;
  case 3:
    // Case for Tuesday
    console.log("Tuesday");
    // Exit the switch statement
    break;
  default:
    // Default case for other days
    console.log("Another day");
}

Output:

Monday

In the example above, the break statement exits the switch statement after the matching case is executed.

Breaking Out of Nested Loops

Example

// Outer loop
for (let i = 0; i < 3; i++) {
  // Inner loop
  for (let j = 0; j < 3; j++) {
    // Check if the inner counter is 1
    if (j === 1) {
      // Exit the inner loop
      break;
    }
    // Print the values of the counters
    console.log(`i = ${i}, j = ${j}`);
  }
}

Output:

i = 0, j = 0
i = 1, j = 0
i = 2, j = 0

In the example above, the break statement exits only the inner loop when j is 1, and the outer loop continues to execute.

Simple Programs using the break Statement

Program 1: Find the First Even Number in an Array

// Define an array of numbers
let numbers = [1, 3, 5, 8, 10];

// Loop through the array
for (let i = 0; i < numbers.length; i++) {
  // Check if the current number is even
  if (numbers[i] % 2 === 0) {
    // Print the first even number
    console.log("First even number:", numbers[i]);
    // Exit the loop
    break;
  }
}

Output:

First even number: 8

Program 2: Search for a Character in a String

// Define the string to search
let str = "hello world";
// Define the character to find
let charToFind = 'o';

// Loop through the string
for (let i = 0; i < str.length; i++) {
  // Check if the current character matches the character to find
  if (str[i] === charToFind) {
    // Print the index of the character
    console.log("Character found at index:", i);
    // Exit the loop
    break;
  }
}

Output:

Character found at index: 4

Program 3: Check for Prime Number

// Define the number to check
let number = 17;
// Initialize a flag to indicate if the number is prime
let isPrime = true;

// Loop from 2 to the square root of the number
for (let i = 2; i <= Math.sqrt(number); i++) {
  // Check if the number is divisible by the current value of i
  if (number % i === 0) {
    // Set the flag to false if the number is not prime
    isPrime = false;
    // Exit the loop
    break;
  }
}

// Check if the number is prime
if (isPrime) {
  console.log(number + " is a prime number.");
} else {
  console.log(number + " is not a prime number.");
}

Output:

17 is a prime number.

Conclusion

In this chapter, you learned about the JavaScript break statement, including its syntax and how to use it in loops and switch statements. We also covered breaking out of nested loops and provided various use cases with simple programs to demonstrate the usage of the break statement. The break statement is used for controlling the flow of your code and exiting loops or switch statements prematurely. In the next chapter, we will explore the JavaScript continue statement and how to use it to skip iterations in loops.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top