Syntax, Parameter and Return Value
Syntax:
_.forEach(collection, [iteratee=_.identity])
Parameters:
-
collection (Array|Object): The collection to iterate over.
- [iteratee=_.identity] (Function): The function invoked per iteration.
Return Value:
Returns the original collection.
Examples
Iterating Over Array Elements:
JavaScript
var _ = require('lodash');
var numbers = [1, 2, 3];
_.forEach(numbers, value => console.log(value * 2));
You can also try this code with Online Javascript Compiler
Run Code
Output:
2, 4, 6
Demonstrates basic iteration over an array with a function applied to each element.
Processing Object Properties:
JavaScript
var user = { 'name': 'John', 'age': 30 };
_.forEach(user, (value, key) => console.log(key, value));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'name' John, 'age' 30
Shows how to iterate over the properties of an object.
Breaking the Loop:
JavaScript
_.forEach(numbers, (value) => {
if (value === 2) return false; // Breaks the loop
console.log(value);
});
You can also try this code with Online Javascript Compiler
Run Code
Output:
1
Illustrates stopping iteration based on a condition.
Iteration Over a String:
JavaScript
var string = 'hello';
_.forEach(string, char => console.log(char.toUpperCase()));
You can also try this code with Online Javascript Compiler
Run Code
Output:
H, E, L, L, O
An example of iterating over each character in a string.
Frequently Asked Questions
How does _.forEach() differ from native JavaScript forEach?
Lodash's _.forEach() works with a wider range of collections, including objects and strings, and allows for early exit from iteration by returning false.
Can _.forEach() modify the original collection?
Yes, if the iteratee function modifies the elements, the changes will reflect in the original collection.
Is _.forEach() efficient for large collections?
_.forEach() is generally efficient for large collections, but performance may vary based on the complexity of the iteratee function.
Conclusion
Lodash's _.forEach() method is a versatile tool for iterating over and processing elements in various types of collections. It provides an intuitive and flexible approach to iteration, enhancing code readability and maintainability, especially when dealing with complex collections.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.