How Lodash findLastKey Iterates Over Object Keys

The _.findLastKey method in Lodash allows developers to inspect an object and return the key of the first element that satisfies a given predicate function, inspecting properties in reverse order. This article explains the internal mechanics of how _.findLastKey iterates through an object's keys, covering property resolution, traversal sequence, predicate evaluation, and early termination.

Key Retrieval and Ordering

Before iteration begins, Lodash retrieves the enumerable own property keys of the target object. In modern JavaScript environments, this retrieval relies on the language's standard property iteration order defined in the ECMAScript specification:

  1. Integer indices in ascending numerical order.
  2. String keys in chronological insertion order.
  3. Symbol keys (if supported by the specific iterator implementation, though standard _.findLastKey targets string-keyed properties).

Lodash abstracts this retrieval through its internal keys function, effectively gathering the property names into an indexed list.

Reverse Traversal Mechanics

Once the array of keys is determined, _.findLastKey delegates the search to internal utilities such as baseFindKey configured for reverse iteration (similar to baseForOwnRight).

Rather than starting at index 0, the iterator initializes a pointer at the end of the keys array:

\[\text{index} = \text{keys.length} - 1\]

The algorithm steps backward through the array, decrementing the pointer by one in each iteration until it reaches index 0.

Predicate Execution and Short-Circuiting

During each step of the backward loop, Lodash accesses the key at the current index and evaluates the user-defined predicate function:

predicate(object[key], key, object)

The iteration operates with short-circuit evaluation:

Code Example

Consider the following object and operation:

const _ = require('lodash');

const users = {
  barney: { age: 36, active: true },
  fred:   { age: 40, active: false },
  pebbles: { age: 1,  active: true }
};

const result = _.findLastKey(users, user => user.active);
  1. Lodash resolves the keys: ['barney', 'fred', 'pebbles'].
  2. Iteration begins at index 2 ('pebbles').
  3. The predicate evaluates users['pebbles'].active, which is true.
  4. The method short-circuits and immediately returns 'pebbles' without inspecting 'fred' or 'barney'.