How Lodash _.eachRight Iterates in Reverse Order

The _.eachRight method in the Lodash JavaScript library—also aliased as _.forEachRight—is an iteration utility designed to traverse collections from right to left, or from the last element to the first. This article explains how _.eachRight executes reverse iteration across arrays and objects, the mechanics of its internal indexing, how early exits work, and practical scenarios where iterating backwards is beneficial.

What is Lodash _.eachRight?

_.eachRight is the reverse counterpart to _.forEach (or _.each). It accepts a collection (an array or object) and an iteratee function, applying the iteratee to every element starting from the end of the collection and moving toward the beginning.

Syntax

_.eachRight(collection, [iteratee=_.identity])

The iteratee function is invoked with three arguments:

  1. value: The current element being processed.
  2. index or key: The index (for arrays) or property key (for objects).
  3. collection: The original collection being traversed.

How Reverse Iteration Works Internally

1. Array Iteration Mechanics

When applied to an array-like structure, _.eachRight relies on a decrementing loop:

  1. Length Determination: It checks the length property of the collection.
  2. Pointer Initialization: The internal index pointer is set to length - 1.
  3. Decrementing Step: With each cycle, the index is decremented by one (index--) until it drops below 0.
  4. Execution: The iteratee is called with (array[index], index, array).
const numbers = [10, 20, 30];

_.eachRight(numbers, (value, index) => {
  console.log(`Index: ${index}, Value: ${value}`);
});

// Output:
// Index: 2, Value: 30
// Index: 1, Value: 20
// Index: 0, Value: 10

2. Object Iteration Mechanics

When iterating over plain objects, JavaScript does not guarantee property insertion order in every scenario, but modern engines maintain key order based on insertion for non-numeric keys.

  1. Key Extraction: Lodash extracts the object's enumerable own property keys (similar to Object.keys()) into an internal array.
  2. Reverse Traversal: It then traverses this array of keys backwards, from keys.length - 1 down to 0.
  3. Execution: The iteratee is called with (object[key], key, object).
const user = { a: 1, b: 2, c: 3 };

_.eachRight(user, (value, key) => {
  console.log(`${key}: ${value}`);
});

// Output:
// c: 3
// b: 2
// a: 1

Halting Iteration Early

Standard JavaScript iteration methods like Array.prototype.forEach do not allow you to break out of the loop without throwing an exception. Lodash's _.eachRight allows early termination: if the iteratee explicitly returns false, iteration stops immediately.

const items = [1, 2, 3, 4, 5];

_.eachRight(items, (value) => {
  if (value === 3) {
    return false; // Halts iteration
  }
  console.log(value);
});

// Output:
// 5
// 4

Key Use Cases for Reverse Iteration