Currying is a functional programming technique that involves breaking down a function that takes multiple arguments into a series of functions that each take a single argument. This makes your functions more flexible and reusable, as you can create specialized versions of a function by pre-setting some arguments.
In web apps, currying can be useful in scenarios like event handling, configuration settings, or when you need to create a series of similar operations but with different initial parameters.
// Using bind()
let multiply = function (x, y) {
console.log("x:", x);
console.log("y:", y);
console.log("Result with bind:", x * y);
};
let multiplyByTwo = multiply.bind(null, 2);
multiplyByTwo(5); // Outputs: x: 2, y: 5, Result with bind: 10
// Using closure
let cMultiply = function (x) {
return function (y) {
console.log("cx:", x);
console.log("cy:", y);
console.log("Result with closure:", x * y);
};
};
let cmultiplyByTwo = cMultiply(2);
cmultiplyByTwo(5); // Outputs: cx: 2, cy: 5, Result with closure: 10
-
Using
bind()
:- Here, we have a
multiply
function that takes two argumentsx
andy
. - We create a new function
multiplyByTwo
by binding the first argument (x
) to2
. null
is passed as the first argument tobind()
becausebind()
expects the first argument to be thethis
value for the new function. Sincemultiply
does not rely onthis
, passingnull
effectively ignores thethis
context.- When we call
multiplyByTwo(5)
, it automatically uses2
as the first argument, and5
as the second. - This is a basic example of currying using
bind()
, where the2
is pre-set.
- Here, we have a
-
Using a Closure:
- In the closure example, we create a function
cMultiply
that takesx
as an argument and returns another function that takesy
. - When we call
cMultiply(2)
, it returns a new function that has2
stored asx
. - Then, calling this new function with
5
multiplies the stored2
by5
, giving us the result. - This is currying using closures, where each function remembers the argument it was called with.
- In the closure example, we create a function