The JavaScript break statement breaks out or exits the current loop, switch statement , or a labeled block. It is a very useful statement, which helps us to exit the loop midway when a certain condition occurs. The break transfers the control to the very next statement after the loop, switch, or a labeled block.
The Syntax of the break statement is as follows.
break [label];
Where the label is optional. Use it to correctly identify which loop to exit in the case of a nested loop. It is a must if you want to exit out of a labeled block
In the following example, the if statement breaks out when the value of i is 6. The values 6 to 10 are never printed as the for loop terminates after the break.
for (let i = 0; i < 10; i++) {
if (i == 6) break;
console.log(i);
}
*** Console ***
0
1
2
3
4
5
Similarly, we break out here when the value of num2 is 3.
let num2 = 0;
while (num2 < 6) {
if (num2 === 3) {
break;
}
num2 = num2 + 1;
}
console.log(num2);
The Switch statements use the Break to break out of the switch. Otherwise, the execution of the switch continues to the next case clause.
//Exapmple 1
let val1 = 20;
let val2 = 10;
let operation = "-";
console.log("switch example");
switch (operation) {
case "+":
console.log(val1 + val2);
break;
case "-":
console.log(val1 - val2);
break;
case "*":
console.log(val1 * val2);
break;
case "/":
console.log(val1 / val2);
break;
default:
console.log("Invalid operator");
}
console.log("switch finished");
In the following code, we have a nested for loop.
The break statement here exits the inner loop and not from the outer loop.
let i = 0;
let j = 0;
let sum = 0;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (i == 6) break;
}
}
console.log(i); //10
console.log(j); //10
In the following example, we prefix the outer loop with outerloop label. And inner loop with innerloop label.
In the break statement, we use the outerloop, which will make the break to exit from the outer loop
outerloop: for (i = 0; i < 10; i++) {
innerloop: for (j = 0; j < 10; j++) {
if (i == 6) break outerloop;
}
}
console.log(i); //6
console.log(j); //0
In the following example, we have two blocks outer & inner. The statement break outer; will exit from the outer block.
let count = 1;
outer: {
inner: {
console.log(count);
break outer;
count++;
console.log(count);
}
count++;
console.log(count);
}
console.log(count); //1
The following results in a syntax error. The break statement can only exit out of a block, loop, or a switch, which it is part of.
In the following example, the break cannot exit blk2, because it is not part of it. It can only exit from the blk1. Hence the following code results in an error.
let z = 0;
blk1: {
console.log(z);
break blk2;
}
blk2: {
console.log(z);
}
console.log(z); //1