Open In App

JavaScript Label Statement

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript label statement is used to label a block of code. A labeled statement can be used with loops and control flow statements to provide a target for the break and continue statements.

Example 1: Using the break statement with labeled loops. we can terminate the outer loop from the inner loop.

JavaScript
let 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++;
    }
}

Output
sum = 1
sum = 3
sum = 4
sum = 6
sum = 7
sum = 9
sum = 10
sum = 12

Example 2: Using the continue statement with labeled loops, we can jump to the outer loop from the inner loop.

JavaScript
let 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++;
      }
}

Output
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, we can terminate the execution of a labeled block.

JavaScript
blockOfCode: {
    console.log('This part will be executed');
    break blockOfCode;
    console.log('this part will not be executed');
}
console.log('out of the block');

Output
This part will be executed
out of the block

Example 4: Labeled function declaration. myLabel is the label assigned to the function declaration. myLabeledFunction is the name of the function.

JavaScript
myLabel: function myLabeledFunction() {
    console.log("This is a labeled function.");
}

// Calling the labeled function
myLabeledFunction();

Output
This is a labeled function.



Next Article

Similar Reads