How to Curry Function in JavaScript: Simple Guide and Examples
To curry a function in JavaScript, you create a new function that takes one argument at a time and returns another function until all arguments are received. Use nested functions or arrow functions to return these intermediate functions, allowing partial application of arguments with
currying.Syntax
Currying transforms a function with multiple arguments into a sequence of functions each taking a single argument.
The general syntax uses nested functions or arrow functions returning another function until all arguments are collected.
javascript
const curriedFunction = arg1 => arg2 => arg3 => { // function body using arg1, arg2, arg3 return result; };
Example
This example shows a curried function that adds three numbers by taking one argument at a time.
javascript
const add = a => b => c => a + b + c; console.log(add(1)(2)(3));
Output
6
Common Pitfalls
One common mistake is calling the curried function with all arguments at once instead of one by one, which will not work as expected.
Another is forgetting to return the inner function, which breaks the chain.
javascript
/* Wrong way: all arguments at once */ const addWrong = a => b => c => a + b + c; // addWrong(1, 2, 3) // undefined or error /* Right way: call one argument at a time */ const addRight = a => b => c => a + b + c; console.log(addRight(1)(2)(3)); // 6
Output
6
Quick Reference
- Currying breaks a function into unary functions.
- Each function takes one argument and returns another function.
- Final function returns the result.
- Use arrow functions for concise syntax.
Key Takeaways
Currying transforms a multi-argument function into a chain of single-argument functions.
Always return the next function to continue the chain.
Call curried functions one argument at a time, not all at once.
Arrow functions make currying syntax clean and readable.
Currying helps create reusable and partially applied functions.