How Lodash endsWith Checks Suffixes at Custom Positions

Lodash's _.endsWith method provides a reliable utility for checking whether a string terminates with a specific target substring. Beyond basic suffix verification, it accepts an optional position parameter that restricts the search space, effectively treating a designated index as the end of the string. This overview explains how _.endsWith interprets custom positions, processes string bounds, and compares against modern JavaScript equivalents.

Syntax and Parameters

The method signature for _.endsWith is defined as follows:

_.endsWith([string=''], [target], [position=string.length])

How Custom Positions Function

Under the hood, _.endsWith uses the position argument to define a virtual boundary within the string. Instead of searching from the absolute end of the input, the function treats the character directly preceding position as the final character.

Internally, the logic proceeds through these steps:

  1. Boundary Normalization: The input position is clamped between 0 and string.length. If the provided position is greater than the string's length, it defaults to the full length. If position is negative, it resolves to 0.
  2. Offset Calculation: The starting index for the comparison is calculated by subtracting the length of the target substring from the normalized position: start = position - target.length.
  3. Substring Comparison: The function checks if the slice of the string from start to position strictly equals target.
const string = 'hello world';

// Standard check (position defaults to string.length, 11)
_.endsWith(string, 'world'); 
// => true

// Custom position set to 5 ('hello')
_.endsWith(string, 'hello', 5); 
// => true

// Custom position set to 4 ('hell')
_.endsWith(string, 'll', 4); 
// => true

Boundary and Edge Case Behavior

When working with custom positions, _.endsWith handles edge cases safely:

Comparison with Native String.prototype.endsWith()

Modern ECMAScript provides a built-in String.prototype.endsWith(searchString, endPosition) method that shares the same functional behavior as Lodash's implementation. The key advantage of using _.endsWith in legacy or mixed environments is its built-in type coercion, which handles null, undefined, and unexpected non-string data types without throwing a TypeError.