Search code examples
javascriptloopsgotolabeled-statements

HTML JAVASCRIPT goto label?


I need your help, I wish to do a "goto" like "goto" in batch :

:loop1
goto loop1

but in javascript for html page, all my research are useless... it can be so usefull to know that !

in my case i need this code because i change a the same 'block of code' many times in different function, and there are to much variable to parse ... so it can help my a lot

here a simple exemple of what i want to do :

    for (var i=0; i < 999; i++) {
        //some code here
        goto go_to_1;
        go_to_2:
        //some code here
        };
    
    for (var i=0; i < 5; i++) {
        //some different code here
        goto go_to_1;
        go_to_2:
        //some different code here
        };
    
    function mytest () {
        for (var i=0; i < 100; i++) {
            //again some different code here
            goto go_to_1;
            go_to_2:
            //again some different code here
            };
        };


    go_to_1:
    //code here
    //always the same code here ,i change it many times
    temp = "library"+i+"";
    //code here 
    goto go_to_2;   

is that possible? how use the "goto" function in javascript?


Solution

  • JavaScript has NO goto statement, you can only use labels with the break or continue.

    You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

    var i, j;
    
    loop1:
    for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
       loop2:
       for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
          if (i === 1 && j === 1) {
             continue loop1;
          }
          log.innerHTML += ('i = ' + i + ', j = ' + j + "<br/>");
       }
    }
    <div id="log"> </div>

    Please Take a look at these:

    mozilla developers - js label

    stackoverflow - js label