Reading list Switch to dark mode

    Label in Javascript

    Updated 30 August 2018

    While working with loops you might come across a situation where you want to exit a loop. Of course you can use break and continue statement to achieve this.But if you have multi level loops i.e loop within loop, and you want to exit through the outer level loop?.Break and continue statements are used to exit the current loop only , and let me tell you javascript do not have goto statement. Here comes Label to rescue.

    Label statement works as an identifier to identify a loop.You can use label statement with break and continue to break or continue the execution.We can create a label by using label name followed by colon.
    Syntax
    nameofthelabel:

    A working example always speaks better than theoretical definition.So lets understand with an example.

    var x, y;
    
    outerloop: // label named as outerloop
    for (x = 0; x < 4; x++) 
    {
        innerloop: // label named as innerloop
        for (y = 0; y < 3; y++) 
        {
           if (x == 1 && y == 1)
              continue innerloop;
    
           if (x == 2 && y == 2)
              continue outerloop;
    
    
           console.log('x = ' + x + ', y = ' + y);
         }
    }

    Output of the above script would be as follows.

    x = 0, y = 0
    x = 0, y = 1
    x = 0, y = 2
    x = 1, y = 0
    x = 1, y = 2
    x = 2, y = 0
    x = 2, y = 1
    x = 3, y = 0
    x = 3, y = 1
    x = 3, y = 2

    Start your headless eCommerce
    now.
    Find out More

    As you can see x=1, y=1 and x=2 ,y=2 output is missing in the output.
    In the script i have labelled outer loop as outerloop and inner loop as innerloop.

    if (x == 1 && y == 1)
       continue innerloop;
    

    Here when x and y equals to 1 we stopped the further execution and continued the innerloop using “continue innerloop” statement.That is why we do not see x=1,y=1 in the output.

    if (x == 2 && y == 2)
       continue outerloop;
    

    Here when x and y equals to 2 we stopped the further execution and continued the outerloop using “continue outerloop” statement.That is why we do not see x=2,y=2 in the output.

     

    I hope using above example i have explained how label works.You can also use break statement .

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home