Skip to content
Related Articles

Related Articles

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.

Let’s understand further with some examples.

for loop with continue statement:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



0
2

for loop with Break Statement:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0
2

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :