EN
JavaScript - break statement
0
points
In this article, we would like to show you break statement in JavaScript.
Syntax
break [label];
Description
The break statement ends the current loop, switch, or label statement and proceeds to the statement following the ended statement.
Practical examples
Example 1 - while loop
In this example, we use break
statement to terminate the while
loop on the specific condition.
// ONLINE-RUNNER:browser;
let i = 0;
while (i < 5) {
if (i === 2) {
break;
}
i = i + 1;
}
console.log(i); // 2
Note:
If the statement we want to break is not a loop or switch,
label
is required.
Example 2 - switch
In this example, we use the break
statement to terminate the switch
statement when a case is matched and the corresponding code has been executed.
// ONLINE-RUNNER:browser;
const number = 2;
switch (number) {
case 1:
console.log('case 1 message...');
break;
case 2:
console.log('case 2 message...');
break;
default:
console.log('default message...');
break;
}