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

 




Reffered: https://www.geeksforgeeks.org


Web Technologies

Related
How to Create a Child Theme in WordPress? How to Create a Child Theme in WordPress?
What is BlogVault plugin in WordPress ? What is BlogVault plugin in WordPress ?
How to add product price in woocommerce ? How to add product price in woocommerce ?
What is Ninja Form in WordPress ? What is Ninja Form in WordPress ?
How to check element exists or not in jQuery ? How to check element exists or not in jQuery ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
9