Open In App

How to ignore loop in else condition using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see the methods to ignore the loop in the else conditions using JavaScript. There are two ways to ignore the loop in the else condition:

Please see this, for explanations of the same. In simple terms, The Break statement exits out of the loop while the continue statement exits out of the particular iteration. Let’s understand this further with some examples. 

Example 1: for loop with continue statement: 

javascript




<script type="text/javascript" charset="utf-8">
    // Defining the variable
    var i;
      
    // For loop
    for (i = 0; i < 3; i++) {
          
        // If i is equal to 1, it
        // skips the iteration
        if (i === 1) { continue; }
      
        // Printing i
        console.log(i);
    }
</script>


Output:

0
2

Example 2: for loop with Break Statement: 

javascript




<script type="text/javascript" charset="utf-8">
    // Defining the variable
    var i;
      
    // For loop
    for (i = 0; i < 3; i++) {
      
        // If i is equal to 1, it comes
        // out of the for a loop
        if (i === 1) { break; }
      
        // Printing i
        console.log(i);
    }
</script>


Output:

0

For eachloop: AngularJS gets pretty messy with break and continue statements when it comes to the forEach loop. The break and continue statements do not work as expected, the best way to implement continue would be to use return statements, the break cannot be implemented in the forEach loop. 

javascript




// Loop which runs through the array [0, 1, 2]
// and ignores when the element is 1
angular.forEach([0, 1, 2], function(count){
    if(count == 1) {
        return true;
    }
  
    // Printing the element
    console.log(count);
});


Output:

0
2

However, the action of break can be achieved by including a boolean function, as implemented in the example below: 

javascript




// A Boolean variable
var flag = true;
  
// forEach loop which iterates through
// the array [0, 1, 2]
angular.forEach([0, 1, 2], function(count){
      
    // If the count equals 1 we
    // set the flag to false
    if(count==1) {
        flag = false;
    }
  
    // If the flag is true we print the count
    if(flag){ console.log(count); }
});


Output:

0


Last Updated : 06 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads