Lodash eachRight and Prototype Chain Traversal

This article explains how the Lodash utility function _.eachRight (also known as _.forEachRight) behaves regarding prototype chain traversal when iterating over JavaScript objects. In short, _.eachRight completely ignores the prototype chain by only processing an object's own enumerable properties in reverse order. Below, we break down the internal mechanics that enforce this behavior, why inherited properties are omitted, and which alternatives to use if prototype inspection is required.

Own Properties vs. Prototype Traversal

When passed a plain JavaScript object, _.eachRight does not traverse the prototype chain. Instead, it restricts its execution strictly to the target object's direct properties.

If an object inherits properties via Object.create() or through ES6 class extension, those inherited properties are deliberately omitted from the iteration loop.

How Lodash Enforces This Internally

The reason _.eachRight avoids prototype chain traversal lies in how it extracts keys before iterating:

  1. Key Extraction: When an object is supplied, Lodash converts the collection into an iterable set of keys using internal helpers analogous to Object.keys(). In the Lodash source code, this is handled by baseKeys.
  2. Reverse Indexing: Once the list of own enumerable keys is captured as an array, Lodash loops through the indices from the last element down to zero (length - 1 down to 0).
  3. Property Invocation: For each key in that reversed list, the provided iteratee callback is invoked with (value, key, object).

Because the underlying key retrieval mechanism only targets own enumerable properties, prototype properties are never captured in the keys array, preventing the iteration loop from ever reaching them.

Contrast with _.forInRight

If your use case explicitly requires traversing the prototype chain in reverse order, _.eachRight is not the correct function. Lodash separates "own property" iteration from "inherited property" iteration:

By restricting _.eachRight to own properties, Lodash prevents unexpected side effects and performance hits associated with deeply nested or polluted prototype chains.