Statement "Return" does not work within foreach. Why?

Asked

Viewed 1,206 times

2

I have the following code snippet, which is executed when trying to insert an item into $scope.items{}:

$scope.items.forEach(function(item, i) {
    if (item.codigo == $('#codigo').val()) {
        item.quantidade = parseInt(item.quantidade) + parseInt($('#quantidade').val());
        return;
    }
});

However, if the condition is met, the return does not interrupt the rest of the code.

Outside the forEach, the return works normally, preventing the rest of the function from continuing to run.

3 answers

5


The return works only for the scope of the function being called, in which case is the forEach. To interrupt it you must make one for conventional:

for (var i = 0; i < $scope.items.length; i++) {
    var item = $scope.items[i];

    if(item.codigo == $('#codigo').val()){
        item.quantidade = parseInt(item.quantidade) + parseInt($('#quantidade').val());
        return;
    }
}

5

If you want to find a specific item and touch it, you have more appropriate methods, such as find:

var item = $scope.items.find(function(item) { 
    return item.codigo == $('#codigo').val(); 
});
item.quantidade = parseInt(item.quantidade) + parseInt($('#quantidade').val());

In ES-2015, cleaner:

let item = $scope.items.find( item => item.codigo == $('#codigo').val() );
item.quantidade = parseInt(item.quantidade) + parseInt($('#quantidade').val());

4

All functions of the Array.prototype iteration, as forEach, map, reduce, filter and every, cannot be stopped. In each case, the value of the return is used for function-dependent decision analysis. In the case of forEach, the return serves to jump to the next element of the array.

Of the documentation of forEach:

There is no way to stop or break a foreach() loop other than by Throwing an Exception. If you need such behavior, the foreach() method is the Wrong tool.

So if you want to iterate over a part, use the sorack’s solution, which is a solution that gives you more freedom on a array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.