The label keyword is not a reserved keyword in JavaScript, but it can be any string. As JavaScript does not include a goto keyword, users can use the continue keyword with the label statement. Furthermore, users can use the break keyword to terminate the loop/block. You can also use the break keyword without defining the label but it terminates only the parent loop/block. To terminate the outer loop from the inner loop using the break keyword, users need to define the label. The following syntax should be followed to define the label statement.
Syntax:
Label: statement (loop or block of code)
Keywords to be used:
- Label: A unique string that is Used to define the name of the block or loop.
- Statement: It can be a loop or block.
- Break: Used to terminate the loop or block of code.
- Continue: Used to terminate or jump from the current iteration of the loop.
Label statement with for loops: In this section, the user will learn to assign a unique label to multiple loops. Also, we will use the break and continue keywords with the multiple loops. The below examples will demonstrate the use of labels using loops.
Example 1: Using the break keyword with labeled loops. Users can terminate the outer loop from the inner loop using the label.
Javascript
<script> var sum = 0, a = 1; // Label for outer loop outerloop: while ( true ) { a = 1; // Label for inner loop innerloop: while (a < 3) { sum += a; if (sum > 12) { // Break outer loop from inner loop break outerloop; } console.log( "sum = " + sum); a++; } } </script> |
Output: We can see that the outer loop terminates when the sum becomes greater than 12.
sum = 1 sum = 3 sum = 4 sum = 6 sum = 7 sum = 9 sum = 10 sum = 12
Example 2: Using the continue keyword with labeled loops. Users can jump to the outer loop from the inner loop using the label.
Javascript
<script> var sum = 0, a = 1; // Label for outerloop outerloop: while (sum < 12) { a = 1; // Label for inner loop innerloop: while (a < 3) { sum += a; if (a === 2 && sum < 12) { // Jump to outer loop from inner loop continue outerloop; } console.log( "sum = " + sum + " a = " + a); a++; } } </script> |
Output: When the ‘ a=2 and sum < 12’ condition executes true, it doesn’t print the sum as we are terminating that iteration of the inner loop using the ‘continue’ keyword. When condition inside if statement executes true, it will jump to the outer loop.
sum = 1 a = 1 sum = 4 a = 1 sum = 7 a = 1 sum = 10 a = 1 sum = 12 a = 2
Example 3: Using the label statement with a block of code. Users can terminate the execution of a labeled block using the break keyword.
Javascript
<script> blockOfCode: { console.log( 'This part will be executed' ); break blockOfCode; console.log( 'this part will not be executed' ); } console.log( 'out of the block' ); </script> |
Output: You can observe that code after the break keyword is not executed
This part will be executed out of the block