What is currying in JavaScript?
Currying transforms a function that takes multiple arguments into a sequence of functions that each take one argument.
How it works — instead of f(a, b, c) you call f(a)(b)(c); each call returns a new function until all arguments are gathered.
Partial application — fix some arguments early and reuse the result with the rest later.
Practical benefit: build specialised functions from general ones — e.g. a generic multiply curried into a reusable double.
// Regular function
function add(a, b, c) {
return a + b + c;
}
add(1, 2, 3); // 6
// Curried version
function curriedAdd(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
curriedAdd(1)(2)(3); // 6
// Arrow function currying (concise)
const multiply = a => b => a * b;
const double = multiply(2); // Partially applied
const triple = multiply(3); // Partially applied
console.log(double(5)); // 10
console.log(triple(5)); // 15
// Generic curry utility
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...more) => curried(...args, ...more);
};
}
const curriedAdd2 = curry((a, b, c) => a + b + c);
console.log(curriedAdd2(1)(2)(3)); // 6
console.log(curriedAdd2(1, 2)(3)); // 6
console.log(curriedAdd2(1)(2, 3)); // 6
// Practical: event handler factory
const handleChange = field => event => {
updateForm({ [field]: event.target.value });
};
// <input onChange={handleChange('email')} />curriedAdd takes one argument at a time, returning functions until all arguments are provided. Arrow syntax makes currying concise: a => b => a * b.
The generic curry utility handles any function — it checks if enough arguments are provided and either calls the original or returns a new partial. The event handler factory is a real-world React pattern.
Show the manual currying, the arrow syntax shorthand, and a practical use case (event handler factory). The generic curry utility shows deep understanding.
Partial application (double = multiply(2)) is the practical benefit.