Break:
In JavaScript, the break statement is a control flow statement used to terminate loops or switch statements prematurely.
Break in Loops:
When break is encountered inside a for, while, or do-while loop, the loop immediately terminates, and program execution continues with the statement following the loop.
JavaScript
for (let i = 0; i < 10; i++) {
if (i === 5) {
console.log("Breaking the loop at i = 5");
break; // Exits the loop
}
console.log(i);
}
// Output:
// 0
// 1
// 2
// 3
// 4
// Breaking the loop at i = 5
break in switch Statements:
Within a switch statement, break is used to exit the switch block after a matching case is executed. Without break, execution would "fall through" to subsequent case blocks.
JavaScript
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the week.");
break; // Exits the switch
case "Tuesday":
console.log("Another day of work.");
break;
default:
console.log("Some other day.");
}
// Output:
// It's the start of the week.
break with Labels:
break can also be used with a label to exit a specific labeled statement, particularly useful for breaking out of nested loops.
JavaScript
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
console.log("Breaking out of outerLoop");
break outerLoop; // Exits both innerLoop and outerLoop
}
console.log(`i: ${i}, j: ${j}`);
}
}
// Output:
// i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// i: 1, j: 0
// Breaking out of outerLoop
Continue:
The continue statement skips the current iteration in a loop.
The remaining code in the iteration is skipped and processing moves to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i is 3
}
console.log(i);
}
// Output:
// 1
// 2
// 4
// 5
break the current iteration if condition is true the output is displayed before you see
Top comments (0)