269

I have an angular foreach loop and i want to break from loop if i match a value. The following code does not work.

angular.forEach([0,1,2], function(count){
  if(count == 1){
    break;
  }
});

How can i get this?

1
  • 1
    I don't understand why you don't just find the value instead of going into a loop. Maybe the example you gave isn't telling the entire story, but I'd rather do what @Aman said below. Why go into the loop as mentioned below and run a check every time when some() does exactly that in a more elegant fashion. Remember that if you treat javascript as a functional language, there should be no point in using these for/while/break type of control structures. That's why foreach, find, some, etc exist Nov 2, 2013 at 23:30

21 Answers 21

308

The angular.forEach loop can't break on a condition match.

My personal advice is to use a NATIVE FOR loop instead of angular.forEach.

The NATIVE FOR loop is around 90% faster then other for loops.

For loop break , for loop test result

USE FOR loop IN ANGULAR:

var numbers = [0, 1, 2, 3, 4, 5];

for (var i = 0, len = numbers.length; i < len; i++) {
  if (numbers[i] === 1) {
    console.log('Loop is going to break.'); 
    break;
  }
  console.log('Loop will continue.');
}
10
  • 1
    This does not work for me. All it does is finish this particular iteration of the loop. But then it moves on to the next iteration.
    – Ben
    Jan 1, 2014 at 14:03
  • 1
    @Ben , Sorry ben , It was my mistake but now i update my answer after long research . I hope this will help you . Thank you
    – Nishchit
    Jan 2, 2014 at 6:55
  • 1
    @LGama :- What is your case ??
    – Nishchit
    Apr 11, 2014 at 5:24
  • 3
    jsperf.com/angular-foreach-performance test it on your own browser to decide which function you should choose. I have tested on IE11 and it is also as fast as in the screenshot. Also tested Array.some() but it is slower then Array.forEach() on IE11 but could be faster then angular.foreach ;-). Or test it here jsperf.com/angular-foreach-vs-native (all credits go to the original author, not me ;-))
    – Sebastian
    Jul 29, 2014 at 9:07
  • 6
    Even with jsperf you cannot say "native for is around 90% faster". In your scenario this highly depends on how expensive the execution of the inner function is and how many executions can be saved by exiting the loop (break) early.
    – hgoebl
    Mar 12, 2015 at 13:54
276

There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:

var keepGoing = true;
angular.forEach([0,1,2], function(count){
  if(keepGoing) {
    if(count == 1){
      keepGoing = false;
    }
  }
});
4
  • 46
    I would rather just add a !keepGoing && return; to the top of the function, less code. Dec 12, 2012 at 17:34
  • 47
    This is not best practices , here angular forEach loop never break , AND there is nothing to break angular.forEach . Native for loop is around 90 % fast than angular.forEach . So it is better to use native for loop when you want to break on condition match . Thanks
    – Nishchit
    Jan 2, 2014 at 6:58
  • xcatly where I stuck...and this helped..thanks a ton...Anyways I would like to know the reason for making forEach loop unbreakable . If any Oct 4, 2015 at 7:10
  • This should not be the accepted answer for it does not break the forEach loop. It is merly a way to not execute all logic inside the loop.
    – Nebulosar
    Apr 8, 2020 at 13:42
25

please use some or every instances of ForEach,

Array.prototype.some:
some is much the same as forEach but it break when the callback returns true

Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.

Example for some:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.some(function (value, index, _ary) {
    console.log(index + ": " + value);
    return value === "JavaScript";
});

Example for every:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.every(function(value, index, _ary) {
    console.log(index + ": " + value);
    return value.indexOf("Script") > -1;
});

Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/

1
  • no @AngelS.Moreno, everyone prefer to use a local variable instead of a method designed specifically for the case in hand
    – Oded Niv
    May 11, 2017 at 13:33
19

Use the Array Some Method

 var exists = [0,1,2].some(function(count){
      return count == 1
 });

exists will return true, and you can use this as a variable in your function

if(exists){
    console.log('this is true!')
}

Array Some Method - Javascript

2
6

As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).

http://underscorejs.org/#find

2
  • this might solve the problem laterally, but it does not in deed break the loop. Apr 13, 2015 at 22:46
  • Or native for loop
    – shanti
    Jan 4, 2017 at 17:59
6

If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.

JSFiddle:

http://jsfiddle.net/JEcD2/1/

Javascript:

var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
    if (element === 'foo') {
        return true; // continue
    }
    console.log(this);
    if (element === 'bar') {
        return false; // break
    }
});

Note:

Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:

"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"

Following examples are provided by MDN:

Array.some:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

Array.every:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
6

Concretely, you can exit of a forEach loop, and of any place, throw an exception.

try {
   angular.forEach([1,2,3], function(num) {
      if (num === 2) throw Error();
   });
} catch(e) {
    // anything
}

However, it is better if you use other library or implement your own function, a find function in this case, so your code is most high-level.

2
  • 10
    Well, you did answer the question! I hope no one does that though :)
    – Jason Cox
    Nov 3, 2015 at 21:42
  • Throwing an exception unnecessarily is not good way of handling the situation. Rather check the solution provided by @dnc253 stackoverflow.com/a/13844508/698127
    – Aamol
    Mar 29, 2017 at 3:02
5

Try this as break;

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return true;
  }
});
3

As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use

jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration
})

See http://api.jquery.com/jquery.each/

1
  • 2
    The OP asked for an AngularJS solution, the correct answer is NO :) Oct 6, 2015 at 1:52
3

Normally there is no way to break an "each" loop in javascript. What can be done usually is to use "short circuit" method.

    array.forEach(function(item) {
      // if the condition is not met, move on to the next round of iteration.
      if (!condition) return;

      // if the condition is met, do your logic here
      console.log('do stuff.')
    }

2

break isn't possible to achieve in angular forEach, we need to modify forEach to do that.

$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];  
                angular.forEach($scope.myuser, function(name){
                  if(name == "Bhushan") {
                    alert(name);
                    return forEach.break(); 
                    //break() is a function that returns an immutable object,e.g. an empty string
                  }
                });
1
  • This answer doesn't seem complete. Please indicate whether break() needs to be defined or wether it's already part of angular. Please define if not.
    – geoidesic
    Sep 29, 2016 at 17:05
2

You can use this:

var count = 0;
var arr = [0,1,2];
for(var i in arr){
   if(count == 1) break;
   //console.log(arr[i]);
}
1
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
    console.log(index)
    keepGoing = true;
    ary.forEach(function(value, index, _ary) {
        if(keepGoing){ 
            if(index==2){
                keepGoing=false;
            }
            else{
                console.log(value)
            }

        }      
    });
});
0
$scope.arr = [0, 1, 2];  
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
    if ( $scope.arr[i] == 1 ) {
        $scope.exists = 'yes, 1 exists';
        break;
    }
 }
 if ( $scope.exists ) {
     angular.forEach ( $scope.arr, function ( value, index ) {
                      $scope.dict[index] = value;
     });
 }
0

I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.

0

I realise this is old, but an array filter may do what you need:

var arr = [0, 1, 2].filter(function (count) {
    return count < 1;
});

You can then run arr.forEach and other array functions.

I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while.

0

This example works. Try it.

var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
  if(i === 1){
   break;
  }
}
1
  • 1
    I guess that he does not want a for loop, his use case needs a foreach not a for probably
    – Hassen Ch.
    May 19, 2017 at 9:28
0

I would use return instead of break.

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return;
  }
});

Works like a charm.

1
  • this is not a valid solution. look: function test() { angular.forEach([1,2,3,4,5,6,7,8,9], function(value, index) { if(value == 2) return; console.log(value); }) } output: > teste(); 1 3 4 5 6 7 8 9 Mar 13, 2019 at 19:24
0

Use Return to break the loop.

angular.forEach([0,1,2], function(count){
  if(count == 1) {
    return;
  }
});
0
onSelectionChanged(event) {
    let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
    let selected_flag = 0;

    selectdata.forEach(data => {
      if (data.selected == true) {
        selected_flag = 1;
      }
    });

    if (selected_flag == 1) {
      this.showForms = true;
    } else {
      this.showForms = false;
    }
}
-2

Just add $index and do the following:

angular.forEach([0,1,2], function(count, $index) {
     if($index !== 1) {
          // do stuff
     }
}
1
  • OP wants to break out of the loop. Jul 27, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.