JavaScript Break Statement
The `break` statement in JavaScript is used to exit from a loop or a `switch` statement. It can be used to terminate the loop execution immediately or to break out of a `switch` statement.
1. Breaking Out of Loops
The `break` statement is commonly used to exit loops early when a specific condition is met. It can be used with `for`, `while`, and `do-while` loops:
// Using break in a for loop
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i);
}
// Output: 0 1 2 3 4
In this example, the `break` statement terminates the loop when `i` equals 5, so the loop only executes until 4.
2. Breaking Out of Switch Statements
In a `switch` statement, the `break` statement is used to prevent the execution from falling through to subsequent `case` blocks:
// Using break in a switch statement
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // Output: Wednesday
Here, the `break` statement prevents the execution from continuing into the `default` case after the `case 3` block executes.