Currying is a functional programming technique that allows us to create reusable and composable functions. It is named after the mathematician Haskell Curry, who introduced the concept.
What is Currying?
Currying is the process of transforming a function that takes multiple arguments into a series of nested functions that each take a single argument. This technique allows us to partially apply arguments to a function, creating new functions with pre-set values.
Example
Let’s take a look at a simple example to understand how currying works in JavaScript.
// Without currying
function add(a, b) {
return a + b;
}
// With currying
function addCurried(a) {
return function(b) {
return a + b;
};
}
// Usage
const add2 = addCurried(2); // This creates a new function with 'a' set to 2
console.log(add2(3)); // Output: 5
In the above example, we have a function called add
that takes two arguments and returns their sum. We also have a curried version of the add
function called addCurried
.
To use the curried function, we first call addCurried(2)
and store the returned function in the variable add2
. This creates a new function with the first argument, a
, set to 2. Then, we call add2(3)
, which adds the second argument, b
, to the pre-set value of a
. The result is 5
.
Benefits of Currying
Currying provides several benefits:
-
Partial Function Application: Currying allows us to partially apply arguments to a function, creating new functions with pre-set values. This can be useful when we want to reuse a function with different initial values.
-
Composition: Curried functions are easier to compose together, creating pipelines of functions that can be applied to data in a modular and flexible way.
-
Curried functions are more reusable: Since curried functions return new functions, we can reuse them in different contexts by applying different arguments.
Implementing Currying in JavaScript
Although JavaScript does not natively support currying, we can easily implement it using either nested functions or currying libraries such as Lodash or Ramda.
Here’s an example of implementing currying using nested functions:
function addCurried(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
const add = addCurried(2)(3);
console.log(add(4)); // Output: 9
Conclusion
Currying is a powerful technique in functional programming that allows us to create reusable and composable functions. By transforming a function that takes multiple arguments into a series of nested functions, we gain the ability to partially apply arguments and create new functions with pre-set values. This can lead to increased code reusability, modularity, and flexibility in our JavaScript applications.