How Lodash nthArg Extracts Specific Arguments

Lodash's _.nthArg is a higher-order utility function that creates a new function designed to return a specific argument from its invocation. This article explains how _.nthArg operates, how it handles positive and negative indices, its internal mechanics using closures and array indexing, and how it is practically applied in JavaScript development.

The Core Concept of _.nthArg

The signature of the method is _.nthArg([n=0]). Instead of directly extracting a value from a collection, _.nthArg generates a function. When that returned function is executed, it inspects all the arguments supplied to it and retrieves the one located at index n. If no index is provided, n defaults to 0.

const getFirst = _.nthArg(0);
const getThird = _.nthArg(2);

getFirst('a', 'b', 'c'); // => 'a'
getThird('a', 'b', 'c'); // => 'c'

Handling Positive and Negative Indices

The index parameter n determines how the generated function scans its arguments:

const getLast = _.nthArg(-1);
getLast('apple', 'banana', 'cherry'); // => 'cherry'

const getSecondLast = _.nthArg(-2);
getSecondLast('apple', 'banana', 'cherry'); // => 'banana'

How It Works Internally

Under the hood, _.nthArg relies on JavaScript closures and Lodash's internal indexing helpers (such as baseNth).

  1. Closure Creation: When _.nthArg(n) is called, it preserves the target index n within the lexical scope of the returned function.
  2. Argument Gathering: The returned function gathers all arguments into an array using rest parameters (or the arguments object).
  3. Index Normalization: If n is negative, the internal logic adjusts the index by adding it to the total count of received arguments (length + n).
  4. Value Lookup: It performs a direct index lookup on the gathered arguments array and returns the resolved element.

A simplified native equivalent looks like this:

function nthArg(n = 0) {
  return function(...args) {
    const index = n < 0 ? args.length + n : n;
    return args[index];
  };
}

Common Use Cases

The primary benefit of _.nthArg is its utility in functional programming paradigms, where functions are passed as arguments to other functions: