EN
JavaScript - break statement
0 points
In this article, we would like to show you how to use break statement in JavaScript.
In this example, we use break
statement inside a for
loop to terminate the loop when the i
iterator value reaches 3
.
xxxxxxxxxx
1
for (let i = 0; i < 5; i++) {
2
if (i === 3) {
3
break;
4
}
5
console.log(i);
6
}
In this example, we use break
statement to terminate the switch
statement when a case
is matched and its code executes.
xxxxxxxxxx
1
const number = 1;
2
3
switch (number) {
4
case 1:
5
console.log('case 1');
6
break;
7
case 2:
8
console.log('case 2');
9
break;
10
default:
11
console.log('default case');
12
break;
13
}
14
In this example, we use break
statement with outer_block
label to break out both inner_block
and outer_block
.
xxxxxxxxxx
1
outer_block: {
2
inner_block: {
3
console.log('inner block message 1');
4
break outer_block;
5
console.log('inner block message 2'); // will be skipped
6
}
7
console.log('outer block message 1'); // will be skipped
8
}