JavaScript break Statement
The break
statement in JavaScript is used to terminate a loop or switch statement prematurely. This means that if a break
statement is encountered inside a loop or switch statement, the rest of the code inside the block is not executed, and control is transferred to the first statement after the block.
The syntax for the break
statement is as follows:
1break;
The break
statement can be used inside for
, while
, do-while
, and switch
statements. In the context of a loop, the break
statement stops the execution of the current iteration of the loop and moves on to the next statement after the loop.
Here's an example of using the break
statement inside a for
loop:
1for (let i = 1; i <= 10; i++) { 2 if (i === 5) { 3 break; 4 } 5 console.log(i); 6} 7 8// Output: 9// 1 10// 2 11// 3 12// 4
In this example, the for
loop starts at 1
and increments i
by 1
until i
is greater than 10
. The if
statement inside the loop checks if i
is equal to 5
. If the condition is true, the break
statement is executed, and the rest of the loop is not executed. The loop terminates and the output is 1
, 2
, 3
, and 4
.
The break
statement can also be used inside a switch
statement to terminate a case. In this case, the break
statement stops the execution of the current case and transfers control to the next statement after the switch
statement.
Here's an example of using the break
statement inside a switch
statement:
1let value = 2; 2 3switch (value) { 4 case 1: 5 console.log("block 1"); 6 break; 7 case 2: 8 console.log("block 2"); 9 break; 10 default: 11 console.log("not match"); 12} 13 14// Output: 15// block 2
In this example, the value
variable is assigned the value 2
, which corresponds to block 2
. When the switch
statement is executed, it matches the value of value
with the cases in the switch
statement. When it matches the case 2
, the code inside the case is executed, and the break
statement is executed to terminate the case. The code inside the default
case is not executed.