How to use labels to control the Flow in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To control the flow in JavaScript, use labels. A label can be used with break and continue statement to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.

Example

You can try to run the following code to use labels to control the flow, with break statement −

Live Demo

<html>    
   <body>              
      <script>            
         document.write("Entering the loop!<br /> ");            
         outerloop: // This is the label name                      
         for (var i = 0; i < 5; i++) {                
            document.write("Outerloop: " + i + "<br />");                
            innerloop:                
            for (var j = 0; j < 5; j++) {                  
               if (j > 3 ) break ; // Quit the innermost loop                  
               if (i == 2) break innerloop; // Do the same thing                  
               if (i == 4) break outerloop; // Quit the outer loop                  
               document.write("Innerloop: " + j + " <br />");                
            }            
         }                      
         document.write("Exiting the loop!<br /> ");      
      </script>          
   </body>
</html>

Example

You can try to run the following code to use labels to control the flow, with continue statement −

Live Demo

<html>    
   <body>          
      <script>
          document.write("Entering the loop!<br /> ");          
          outerloop: // This is the label name                    
          for (var i = 0; i < 3; i++) {            
             document.write("Outerloop: " + i + "<br />");            
             for (var j = 0; j < 5; j++) {                
                if (j == 3){                  
                   continue outerloop;                
                }                
                document.write("Innerloop: " + j + "<br />");            
             }          
          }                    
          document.write("Exiting the loop!<br /> ");            
       </script>          
    </body>
</html>
raja
Published on 23-Apr-2018 17:20:44
Advertisements