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

1 comment:

  1. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    angularjs training in chennai | angularjs training chennai

    ReplyDelete