Open In App

How to break forEach() method in Lodash ?

The Lodash _.forEach() method iterates over elements of the collection and invokes iterate for each element. In this article, we will see how to break the forEach loop in ladash library.

Syntax:



_.forEach( collection, [iterate = _.identity] )

Parameters: This method accepts two parameters as mentioned above and described below:

Problem: To break forEach loop in Lodash break keyword won’t work. If we do so we get a SyntaxError.






<script>
    // Requiring the lodash library 
    const _ = require('lodash');
     
    _.forEach([1, 2, 3, 4], function (value) {
        if (value == 2) return false;
        console.log(value);
    });
</script>

 
 

Output:

 

SyntaxError: Illegal break statement 

Solution: So from this we know we can’t use break statements as they are not valid in Lodash syntax. So we have to return false from the callback function if we have to break the loop.

 




<script>
    // Requiring the lodash library
    const _ = require('lodash');
     
    _.forEach([1, 2, 3, 4], function (value) {
        if (value == 3) {
            return false; // Breaks the forEach
        }
        console.log(value);
    });
</script>

 
 

Output:

 

1
2

Conclusion: Hence to break Lodash forEach loop we have to return false from the callback function.

 


Article Tags :