Skip to main content

JavaScript: Using a labeled break statement

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.
Tags
Submitted by arilio666 on October 11, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.