return does not work inside forEach

1

I have the following code snippet, which is executed when trying to insert an item in $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, return does not interrupt the rest of the code.

Note: outside the loop works normally.

    
asked by anonymous 03.08.2017 / 18:35

3 answers

4

The return works only for the scope of the function being called, in this case it is forEach . To stop it, you must% 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;
    }
}
    
03.08.2017 / 18:39
4

If you want to find a specific item and move 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());
    
03.08.2017 / 19:01
2

All functions in the iteration, such as Array.prototype forEach , map , reduce , filter and every , can not be interrupted. In each of them, the value of return is used for function dependent decision analysis. In the case of forEach , return is to jump to the next element of the array.

From the documentation for 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 solution , which is a solution that gives you more freedom over array .

    
05.08.2017 / 16:38