Open In App

Lodash _.forEach() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.forEach() method iterates over elements of the collection and invokes iteratee for each element.

Syntax:

_.forEach(collection, [iteratee = _.identity]);

Parameters:

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

Return Value:

This method returns the collection. 

Example 1: In this example, we are iterating an array by the use of the _.forEach() method and printing the results in the console.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Use of _.forEach() method
_.forEach(['c', 'cpp', 'java', 'python'], function (value) {
    console.log(value);
});


Output:

'c'
'cpp'
'java'
'python'

Example 2: In this example, we are iterating an object by the use of the _.forEach() method and printing the results in the console.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Use of _.forEach() method
_.forEach({ 'x': 1, 'y': 2 }, function (value, key) {
    console.log(key);
});


Output:

'x'
'y'

Note: This will not work in normal JavaScript because it requires the library lodash to be installed. 

Reference: https://lodash.com/docs/4.17.15#forEach


Last Updated : 25 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads