What is Currying in JavaScript
Currying is a technique of transforming a function with multiple arguments into a sequence of functions, each taking one argument.
Why is Currying Needed?
- Reusability: you can fix some arguments in advance.
- Function purity: curried functions are easier to test and combine.
- Functional style: often used in functional programming.
Simple Example
function sum(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
console.log(sum(1)(2)(3)); // 6
Here sum is a curried function, it takes one argument at a time.
Partial Application
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2); // partially applied function
console.log(double(5)); // 10
Universal Currying Function
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
} else {
return (...next) => curried(...args, ...next);
}
};
}
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6
Difference from Regular Function
| Characteristic | Regular Function | Curried Function |
|---|---|---|
| Call | sum(1, 2, 3) | sum(1)(2)(3) |
| Argument application | All at once | One at a time |
| Reusability | Harder | Easy to fix some arguments |
When to Apply Currying?
- When you need to partially apply arguments
- When using functional style (e.g., with map, filter, reduce)
- When composing complex functions from simple ones
Summary:
Currying is a powerful technique in functional programming. It helps write more modular, readable and reusable code, especially in chains and callbacks.