Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to break forEach() method in Lodash ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

  • collection: This parameter holds the collection to iterate over.
  • iterate: It is the function that is invoked per iteration.

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

Javascript




<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.

 

Javascript




<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.

 


My Personal Notes arrow_drop_up
Last Updated : 18 Feb, 2022
Like Article
Save Article