What is break keyword?
The break keyword is used for
Exiting from a loop
Exiting from a loop to a label
Exiting from a block to a label
Using break keyword
Case 1 : Inside a loop
let i=10; while (true) { i++; if (i>15) break; } console.log("i", i); // 16
In the above code the the while is exited when i is 16.
Case 2: Exiting from a loop to a label
outer: for (let i=0;i<10;i++) { // outer label console.log("for i", i); // for i 0 for (let j=2;j<10;j++) { if (j==5) break outer; } } console.log("after for loop");
In the above code the inner for loop is exited to outer label.
Case 3: Exiting from a code block to a label
flagpost: { // flagpost label console.log("inside block"); break flagpost; console.log("inside block 2"); // not executed } console.log("after code block");
In the above code the code block is exited to label flagpost.
What is continue keyword?
The continue keyword is used for
- To skip instructions in loop and return the control back to start of loop
Using continue Keyword
Case 1
let i=2; while(i<10) { i++; if (i> 6) console.log(i); else continue; console.log("After if"); }
In the above code 'After if' is printed when i is greater than 6. When i less than 7 control is returned back to start of loop.
Case 2
let i=2; while(i<10) { (i < 6) ? console.log(i): continue; i++; }
The above code will yield into error because continue keyword cannot be used with ternary operator.
Complete Code Listing
//Objective : Using break and continue keywords
//Author : Mahavir
let i=10;
while (true) {
i++;
if (i>15)
break;
}
console.log("i", i); // 16
outer: for (let i=0;i<10;i++) { // outer label
console.log("for i", i); // for i 0
for (let j=2;j<10;j++) {
if (j==5)
break outer;
}
}
console.log("after for loop");
flagpost: { // flagpost label
console.log("inside block");
break flagpost;
console.log("inside block 2"); // not executed
}
console.log("after code block");
i=2;
while(i<10) {
i++;
if (i> 6)
console.log(i);
else
continue;
console.log("After if");
}
i=2;
while(i<10) {
(i < 6) ? console.log(i): continue; // error
i++;
}