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:
- Arguments up to
n: The firstnarguments are passed directly to the original function in the exact order and format they were supplied. - Arguments beyond
n: Any arguments supplied past the indexn - 1are completely discarded. The underlying function will have no access to them, even via theargumentsobject or rest parameters (...args), because they are sliced off before the function is called. - Fewer arguments than
n: If fewer thannarguments are supplied, the function is executed normally with the available arguments, leaving unsupplied parameters asundefined. - Default behavior: If
nis not explicitly defined, it defaults to thelengthproperty of the target function, meaning it accepts only as many arguments as the function explicitly declares in its signature.
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.