Bind function arguments
Binding arguments of a function is also known as partial application. It is when the arguments are supplied on different calls. It is useful to make a function more specific.
The textbook example is that instead of separately defining a pow(x, y)
and a square(x)
functions, use partial application, as square(x)
is equivalent to pow(x, 2)
. Also, the binding of the first parameter is possible, as powerOf2(x)
is equal to pow(2, x)
.
Use bind
All functions have a built-in bind
that applies the arguments from left to right. Its syntax is .bind(undefined, ...parameters)
.
const square = Math.pow.bind(undefined, 2);
console.log(square(3)); // 2^3 = 8
Wrap in a partially applied function
What if you want the second argument to be bound? In that case, bind
provides little help.
The best approach is to define a new function that wraps the original one:
const powerOf2 = (first) =>
Math.pow(first, 2);
console.log(powerOf2(3)); // 3^2 = 9
Use a library
Just as for everything else, several libraries provide a generalized way to bind parameters.
For example, Lodash provides a bind
function. Its signature is similar to the native bind
, but it also needs the original function as the first argument.
But it's also more generic, as it supports _.bind.placeholder
to skip parameters. Using this placeholder, any of the parameters can be partially applied.
const powerOf2 = _.bind(Math.pow, undefined, _.bind.placeholder, 2);
console.log(powerOf2(3)); // 3^2 = 9