Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I use currying to transform a function with multiple arguments in JavaScript?
Asked on Dec 20, 2025
Answer
Currying is a functional programming technique that transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for more flexible and reusable function calls.
<!-- BEGIN COPY / PASTE -->
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function(...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // Output: 6
console.log(curriedAdd(1, 2)(3)); // Output: 6
console.log(curriedAdd(1)(2, 3)); // Output: 6
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "curry" function takes a function "fn" as an argument and returns a new function "curried".
- "curried" checks if the number of arguments is sufficient to call "fn". If so, it calls "fn" with those arguments.
- If not, it returns another function to collect more arguments.
- The "add" function is an example of a function that can be curried.
- "curriedAdd" demonstrates how the curried function can be called with different combinations of arguments.
Recommended Links:
