How Lodash nth Calculates Floating-Point Indices
The _.nth function in the Lodash JavaScript library
retrieves the element at index n of an array, supporting
both positive and negative values. When provided with a floating-point
number rather than an integer, Lodash internally normalizes the index by
truncating the decimal component toward zero using internal utility
methods before computing array bounds and retrieving the target
element.
Step 1: Integer Coercion
via toInteger
When _.nth(array, n) is called, the second argument
n is passed through Lodash's internal
toInteger helper function.
Under the hood, toInteger executes the following
sequence:
- It converts the input to a finite number using
toFinite. - It calculates the fractional remainder using the modulo operator:
remainder = result % 1. - It subtracts the remainder from the value:
remainder ? result - remainder : result.
This calculation performs truncation toward zero rather than standard
mathematical rounding (Math.round) or downward rounding
(Math.floor). Consequently:
- An argument of
1.2or1.9truncates to1. - An argument of
-1.2or-1.9truncates to-1. - Special float values like
NaNdefault to0.
Step 2: Negative
Index Resolution via baseNth
Once converted to an integer, the normalized value is forwarded to
the internal baseNth function alongside the array.
Lodash supports negative index querying, where negative numbers count backward from the end of the collection. The calculation is applied as follows:
n += n < 0 ? length : 0;If the truncated integer is negative, baseNth adds the
array's length to determine the corresponding zero-based
positive index:
- For an array with a length of
5, an input of-1.7truncates to-1. - Applying the formula yields
-1 + 5 = 4. - The element at index
4(the final element) is targeted.
Step 3: Index Validation and Access
Finally, Lodash checks if the resolved index satisfies
isIndex(n, length). This verification ensures that the
index is a non-negative integer within the valid range
[0, length - 1].
If the calculated index is valid, array[n] is returned.
If the value falls out of range (for example, if a negative float
resolves past the start of the array), the function safely returns
undefined.
Code Example
const items = ['a', 'b', 'c', 'd'];
// Positive floats truncate downward toward zero
_.nth(items, 1.9); // Truncates to 1 -> returns 'b'
// Negative floats truncate upward toward zero
_.nth(items, -1.9); // Truncates to -1 -> resolves to index 3 -> returns 'd'
_.nth(items, -2.1); // Truncates to -2 -> resolves to index 2 -> returns 'c'