Break statement
The break statement is used to jump out of a loop. It can be used to “jump out” of a switch() statement. It breaks the loop and continues executing the code after the loop.
Example:
let content = "" ;
let i; for (i = 1; i < 1000; i++) {
if (i === 6) {
break ;
}
content += "Geeks" + i + "\n"
} console.log(content); |
Geeks1 Geeks2 Geeks3 Geeks4 Geeks5
Continue statement
The continue statement “jumps over” one iteration in the loop. It breaks iteration in the loop and continues executing the next iteration in the loop.
Example:
let content = "" ;
let i; for (i = 1; i < 7; i++) {
if (i === 4) {
continue ;
}
content += "Geeks" + i + "\n" ;
} console.log(content); |
Geeks1 Geeks2 Geeks3 Geeks5 Geeks6
JavaScript labels
In JavaScript, the label statements are written as statements with a label name and a colon.
Syntax:
-
break statements: It is used to jump out of a loop or a switch without a label reference while with a label reference, it is used to jump out of any code block.
break labelname;
-
continue statements: It used to skip one loop iteration with or without a label reference.
continue labelname;
Example: This example uses break-label statements.
let val = [ "Geeks1" , "Geeks2" , "Geeks3" ,
"Geeks4" , "Geeks5" ];
let print = "" ;
breaklabel: { print += val[0] + "\n" + val[1] + "\n" ;
break breaklabel;
print += val[2] + "\n" + val[3] + "\n" + val[4];
} console.log(print); |
Geeks1 Geeks2
Example: This example uses the continue label.
outer: for (let i = 1; i <= 2; i++) {
inner: for (let j = 1; j <= 2; j++) {
if (j === 2) {
console.log( "Skipping innerLoop iteration" , i, j);
continue inner; // Continue innerLoop iteration
}
console.log( "GeeksInner" , i, j);
}
console.log( "GeeksOuter" , i);
} |
GeeksInner 1 1 Skipping innerLoop iteration 1 2 GeeksOuter 1 GeeksInner 2 1 Skipping innerLoop iteration 2 2 GeeksOuter 2
Example: This example illustrates without using any label.
let val = [ "Geeks1" , "Geeks2" , "Geeks3" , "Geeks4" ];
let val1 = [ "Geeks" , "For" , "Geeks" ]
let print = "" ;
labelloop: { print += val1[0] + "\n" ;
print += val1[1] + "\n" ;
print += val1[2] + "\n" ;
} print += "\n" ;
labelloop1: { print += val[0] + "\n" ;
print += val[1] + "\n" ;
print += val[2] + "\n" ;
print += val[3] + "\n" ;
} console.log(print); |
Geeks For Geeks Geeks1 Geeks2 Geeks3 Geeks4