Lodash sortedLastIndexOf Return Value When Absent

This article explains what Lodash's _.sortedLastIndexOf method returns when searching for a value that does not exist within a sorted array. It details the exact return value, highlights the critical distinction between this function and _.sortedLastIndex, and provides practical JavaScript code examples to demonstrate its behavior in production code.

The Return Value for Absent Elements

When a target value is not found in the provided array, _.sortedLastIndexOf returns -1.

Because it mirrors the behavior of standard JavaScript search methods like Array.prototype.lastIndexOf, it strictly signals non-existence by returning -1 rather than indicating an insertion point or throwing an error.

const _ = require('lodash');

const numbers = [10, 20, 30, 30, 40, 50];

// Searching for a value that exists
console.log(_.sortedLastIndexOf(numbers, 30)); 
// Output: 3 (the highest index of 30)

// Searching for a value that is absent
console.log(_.sortedLastIndexOf(numbers, 25)); 
// Output: -1

_.sortedLastIndexOf vs. _.sortedLastIndex

A common source of confusion in Lodash is the distinction between _.sortedLastIndexOf and _.sortedLastIndex. While their names are nearly identical, their handling of missing values differs significantly:

const numbers = [10, 20, 30, 40];

// Value is absent
console.log(_.sortedLastIndexOf(numbers, 25)); // Output: -1
console.log(_.sortedLastIndex(numbers, 25));     // Output: 2

Important Considerations

To ensure _.sortedLastIndexOf reliably returns -1 for absent values, the input array must be sorted in ascending order. The method uses a binary search algorithm (O(log n) time complexity). If the array is unsorted, the binary search logic will fail, potentially returning -1 for values that are actually present or returning incorrect indices.