Lodash _.ary Method: How Arguments Are Handled

The _.ary method in the Lodash JavaScript library creates a wrapper function that restricts the number of arguments passed to a target function. By capping the argument count at a specified number, _.ary prevents extraneous arguments from being forwarded, ensuring that only the designated initial arguments reach the underlying function while any surplus arguments are ignored.

How Arguments Are Processed

When a function wrapped with _.ary(func, [n=func.length]) is invoked, the method evaluates the arguments provided at call time:

Practical Impact

The primary use case for this behavior is dealing with higher-order functions that pass extra metadata arguments to callbacks. A classic example is Array.prototype.map, which passes three arguments to its callback: (currentValue, index, array).

When using standard JavaScript functions like parseInt inside a map call, passing index as the second argument causes errors because parseInt interprets the second argument as the radix (base):

['6', '8', '10'].map(parseInt);
// Returns [6, NaN, 2] because parseInt evaluates ('8', 1) and ('10', 2)

Applying _.ary restricts the input to only the first argument:

const safeParseInt = _.ary(parseInt, 1);

['6', '8', '10'].map(safeParseInt);
// Returns [6, 8, 10]

In this scenario, _.ary intercepts each call from map, forwards only currentValue, and discards index and array, ensuring parseInt executes with its default radix.