How to ignore loop in else condition using JavaScript ?
Last Updated :
06 Feb, 2023
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" >
var i;
for (i = 0; i < 3; i++) {
if (i === 1) { continue ; }
console.log(i);
}
</script>
|
Output:
0
2
Example 2: for loop with Break Statement:
javascript
<script type= "text/javascript" charset= "utf-8" >
var i;
for (i = 0; i < 3; i++) {
if (i === 1) { break ; }
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
angular.forEach([0, 1, 2], function (count){
if (count == 1) {
return true ;
}
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
var flag = true ;
angular.forEach([0, 1, 2], function (count){
if (count==1) {
flag = false ;
}
if (flag){ console.log(count); }
});
|
Output:
0
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...