Currying
Currying is the process of transforming a function that takes several arguments into a sequence of functions, each of which takes only one argument.
Example:
A regular function:
javascript
function sum(a, b) {
return a + b;
}
sum(2, 3); // 5After currying:
javascript
function curriedSum(a) {
return function (b) {
return a + b;
};
}
curriedSum(2)(3); // 5How it works:
curriedSum(2)returns a new function that "remembers" the valuea = 2.- That function then waits for the second argument
b. - When we call it with
3, it returns the result2 + 3.
Why currying is needed:
- Reusing partially applied functions
javascript
const add10 = curriedSum(10);
add10(5); // 15
add10(7); // 17- Simplifies function composition - useful in functional programming.
- Improves code readability and flexibility, especially in libraries like Lodash or Ramda.
In short:
Currying turns the function
f(a, b, c)intof(a)(b)(c), so it can be called in parts and partial calls can be reused.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.