What Is the Lodash Alias for _.each?

This article covers the alias for the _.each method in the Lodash JavaScript library, detailing what it is, how it works, and how it behaves across collections. You will learn the exact naming convention Lodash uses, the arguments passed to its callback function, and how it compares to native JavaScript iteration methods.

In the Lodash JavaScript library, the alias for _.each is _.forEach. Both method names point to the exact same underlying function within the Lodash Collection module, meaning they can be used interchangeably with identical behavior and performance.

Syntax and Parameters

The syntax for both _.each and _.forEach is as follows:

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

The iteratee function is invoked with three arguments:

  1. value: The current element's value.
  2. index or key: The current element's index (for arrays) or property name (for objects).
  3. collection: The parent collection being iterated.

Key Features and Behavior

Unlike the native JavaScript Array.prototype.forEach, Lodash's _.each (and _.forEach) provides two distinct advantages:

  1. Object Iteration: It operates seamlessly on plain JavaScript objects as well as arrays, eliminating the need to use Object.keys() or Object.entries() beforehand.
  2. Early Termination: You can exit iteration early by explicitly returning false from within the iteratee callback.

Code Example

const _ = require('lodash');

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// Using _.each
_.each(users, (user, index) => {
  if (user.id === 2) {
    return false; // Exits iteration early
  }
  console.log(`Index ${index}: ${user.name}`);
});

// Using _.forEach (identical result)
_.forEach(users, (user, index) => {
  if (user.id === 2) {
    return false; // Exits iteration early
  }
  console.log(`Index ${index}: ${user.name}`);
});

Because _.each is simply a direct reference to _.forEach, choosing between them is entirely a matter of coding style and personal or team preference.