Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to ignore loop in else condition using JavaScript ?

  • Last Updated : 24 Apr, 2020

There are two ways to ignore loop in else condition:

  • Continue
  • Break

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Let’s understand further with some examples.

for loop with continue statement:






// 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);
}

Output:

0
2

for loop with Break Statement:




// 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);
}

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 forEach loop.




// 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:




// 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!