Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to break forEach() method in Lodash ?

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:

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

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments