Break forEach loop in AngularJS (illegal break statement error)

In this article i am going to explain how to break forEach loop in AngularJS

You cannot directly use break statement inside a AngularJS forEach loop. When you try to use, it throws error illeagal break statement.

For example consider you have following array

$scope.users = ['John','Smith','David','Stephen'];

if you have to check whether the given user present in the users array you have to use following angularJS code.

var userNameToCheck = 'Smith';
var userExists = false;
angular.forEach($scope.users, function(userName){
    if(userName == userNameToCheck)
    {
        userExists = true;
    }
});

Above code checks whether the given user name present in the users array or not. If it finds the user in the array then userExists flag will be set to true. But once the user is found we need to get out of the loop in order to avoid unnecessary iterations. But if we directly write break statement inside if condition in angular.forEach loop, it throws error(illegal break statement error).
So, in order to break out of angular.forEach after finding the user, use the following code

var userNameToCheck = 'Smith';
var userExists = false;
angular.forEach($scope.users, function(userName){
    if(!userExists)
    {
        if(userName == userNameToCheck)
        {
            userExists = true;
        }
    }
});

In the above code we added one more if condition which checks whether the userExists flag is already set to true. If it is true that means we already found the user. So no need to check for the other users. 

In this way we can break forEach loop in AngularJS


For more posts on AngularJS visit AngularJS

3 comments:

  1. If i have 1000 rows and found value at 1st record it will be execute 999 times how to stop it

    ReplyDelete
  2. But thru this we can stop enter into if condition, but can't terminate foreach loop..
    Its good that everytime it wont check condition atleast once its already matched. but loop will keep going. It wont stop

    ReplyDelete
    Replies
    1. You are right. But it will be useful when you have one more foreach loop inside main foreach. it will not let the inner foreach loop to iterate once we get what we need.

      Delete