JavaScript: Using a labeled break statement

Profile picture for user arilio666

Javascript label statements are used to prefix that particular label to an identifier. A label can be generally used with the continue and break statements to show and prefix the code more precisely on what is happening.

A label is simply an identifier followed by a colon (:).

So that normally when we use a label we can understand what is happening inside the code block with the label name and also act as a tag to break the block using its name.

Think of it as an alias name that is used for the whole block of the code.

Syntax

break;  //without label
break labelname; //break loop with labelname

Example

var y,z;
BreakLabel:
for (y = 0; y < 6; y++)
{
    for(z=0;z<y;z++)
    {
        if(y==4)
            break BreakLabel;
        console.log(y+"\t");
    }
   console.log()
}
console.log("Outside loop");

Output:

1

2
2

3
3
3

Outside loop
  • So here we have a label named BreakLabel and also our Y and Z initialized outside.
  • So from we have taken two loops and placed a loop within a loop to iterate the Y value within Z and get the series of numbers in the form of count representation.
  • So here we will be using the label called BreakLabel to call the loop to perform the break on it.
  • Provided with the if condition within the loop that when the iteration comes to the point of 4 then the iteration breaks leaving anything comprised of 4 and beyond stops the iteration.
  • This is how we can use the labeled break statement.