Lodash findLast Termination Condition with Set Objects

In the Lodash JavaScript library, _.findLast iterates through a collection in reverse order to return the first element that satisfies a given predicate. When operating on a collection, its termination condition is governed by two fundamental mechanics: an early exit triggered when the predicate function evaluates to a truthy value, or a boundary exit when the iteration counter exhausts all elements. However, because a native JavaScript Set is not treated as an array-like structure by Lodash, understanding how _.findLast determines termination requires examining both its generic iteration logic and how it handles Set structures internally.

The Standard Termination Conditions

Under standard execution on collections, _.findLast terminates based on two specific criteria:

  1. Predicate Match (Early Termination): The function applies the iteratee (predicate) to each element from right to left. The moment the predicate returns a truthy value, iteration stops immediately, and _.findLast returns the matching element.
  2. Index Boundary Exhaustion: The iteration starts at the end of the collection (length - 1 or a user-defined fromIndex) and decrements backwards toward index 0. If the index decrements past zero (i.e., index < 0) without any element satisfying the predicate, the loop terminates and returns undefined.

How Lodash Handles Native Set Objects

In JavaScript, a Set stores unique values and does not possess numeric indices or a .length property; instead, it uses a .size property. Lodash's internal architecture relies on the isArrayLike utility to branch collection processing.

Because isArrayLike(set) returns false, _.findLast routes the Set through its non-array object handler:

  1. Key Extraction via _.keys: Lodash treats the collection as an object and attempts to extract its enumerable own property names using keys(collection).
  2. Empty Key Resolution: Native ES6 Set objects store values internally and do not expose their entries as enumerable own properties. As a result, _.keys(new Set(...)) evaluates to an empty array ([]).
  3. Immediate Termination: Because the extracted keys array has a length of 0, the starting index is calculated as 0 - 1 = -1. The while loop condition (index >= 0) fails immediately on initialization.

Consequently, when _.findLast is invoked directly on a native Set, the termination condition is met instantaneously before any predicate evaluation occurs, and the function returns undefined.

Proper Reverse Searching on a Set

To allow _.findLast to reach elements within a Set and evaluate standard termination conditions, the Set must first be converted into an array or array-like collection:

const mySet = new Set([10, 20, 30, 40]);

// Convert the Set to an array for proper evaluation
const result = _.findLast(Array.from(mySet), (value) => value < 35);
// result: 30

When converted: