Function Currying in JavaScript: What It Is and How It Works
How It Works
Imagine you want to bake a cake, but instead of doing all steps at once, you do them one by one: first mix flour, then add sugar, then eggs, and so on. Function currying works similarly by breaking a function that takes many inputs into smaller functions that each take one input.
In JavaScript, a curried function returns a new function after receiving an argument, waiting for the next argument. This continues until all arguments are provided, then the original function runs with all collected inputs.
This helps in creating reusable and flexible functions by fixing some arguments early and passing others later, like setting part of a recipe before finishing it.
Example
This example shows a simple curried function that adds three numbers, one at a time.
const add = a => b => c => a + b + c; console.log(add(1)(2)(3));
When to Use
Use currying when you want to create specialized functions by fixing some arguments early and reuse them later. For example, if you have a function that formats messages, you can fix the greeting part and reuse it for different names.
Currying is helpful in functional programming, event handling, and when working with libraries that expect functions with single arguments. It makes your code more modular and easier to test.
Key Points
- Currying transforms a multi-argument function into a chain of single-argument functions.
- It allows partial application of functions by fixing some arguments early.
- Currying improves code reuse and modularity.
- It is widely used in functional programming styles.