Lodash _.nth with Negative Index on a String

In the Lodash JavaScript library, passing a negative index to the _.nth function when evaluating a string retrieves the character located at that offset counting backward from the end of the string. This article outlines the internal resolution mechanism used by _.nth, how negative numbers map to specific string positions, and how out-of-bounds indices are handled.

How _.nth Processes Strings

Although primarily used with arrays, _.nth accepts any array-like value, including strings. Strings in JavaScript possess a .length property and zero-based indexed elements. When _.nth evaluates a string, it treats the string as a sequence of single-character elements.

The Negative Index Calculation

When a negative integer is provided as the index argument (n), Lodash calculates the target position by adding the negative integer directly to the string’s length:

\[\text{Resolved Index} = \text{string.length} + n\]

Because the index is negative, this addition offsets the pointer from the end of the string:

Example

const _ = require('lodash');

const word = 'JavaScript';

_.nth(word, -1); // Returns 't'
_.nth(word, -2); // Returns 'p'
_.nth(word, -6); // Returns 'S'

Out-of-Bounds Negative Indices

If the absolute value of the negative index is greater than the length of the string, the resolved index becomes negative. In this scenario, _.nth attempts an invalid property lookup and safely returns undefined. It does not throw an error or wrap around the string repeatedly.

const shortStr = 'cat'; // length is 3

_.nth(shortStr, -3); // Returns 'c' (index 0)
_.nth(shortStr, -4); // Returns undefined (resolved index is -1)