The break statement in JavaScript is used to exit a loop or switch statement before it has completed its natural execution. It immediately terminates the enclosing loop or switch and transfers control to the statement following the terminated statement.
1. Syntax of break Statement:
break;
2. break in a for Loop:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log("i = " + i);
}
Output:
i = 0 i = 1 i = 2 i = 3 i = 4
Explanation:
- The loop stops execution when
iequals 5 due to thebreakstatement.
3. break in a while Loop:
let count = 0;
while (count < 10) {
if (count === 5) {
break;
}
console.log("Count = " + count);
count++;
}
Output:
Count = 0 Count = 1 Count = 2 Count = 3 Count = 4
Explanation:
- The
whileloop stops whencountequals 5 due to thebreakstatement.
4. break in a switch Statement:
let color = "red";
switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color is not red or blue");
}
Output:
Color is red
5. break in Nested Loops:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 2) {
break;
}
console.log(`i = ${i}, j = ${j}`);
}
}
Output:
i = 0, j = 0 i = 0, j = 1 i = 1, j = 0 i = 1, j = 1 i = 2, j = 0 i = 2, j = 1
Explanation:
- The
breakstatement exits the inner loop whenjequals 2 but allows the outer loop to continue.
6. break in a Labeled Statement:
In JavaScript, you can use labels to break out of nested loops or a specific loop. A label identifies a loop or a block of code.
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log(`i = ${i}, j = ${j}`);
}
}
Output:
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 1, j = 0
Explanation:
- The
break outerLoop;statement exits theouterLoopentirely, skipping the remaining iterations.
Conclusion:
- The
breakstatement is a powerful tool for controlling the flow of loops and switch statements. - It allows for more precise and controlled termination of loops and cases, improving code readability and logic management.
- However, use
breakcarefully to ensure that it does not unintentionally terminate the loop or block, leading to unexpected results.