Currying Explained Simply
What is Function Currying?
Function currying is a technique where:
- A function takes one argument at a time
- Instead of taking all arguments together
- It returns another function to accept the next argument
Normal Function vs Curried Function
Normal Function
function add(a, b) {
return a + b;
}
console.log(add(10, 20)); // 30
Here:
- Both arguments (
a,b) are passed together
Curried Function
function add(a) {
return function(b) {
return a + b;
};
}
console.log(add(10)(20)); // 30
How it works:
add(10)→ returns a function- That returned function takes
b = 20 - Final result →
10 + 20 = 30
Step-by-Step Understanding
let result = add(10); // returns a function
console.log(result(20)); // 30
- First call stores partial data
- Second call completes the calculation
Real Use Case (Partial Execution)
Sometimes:
- You don’t have all data at once
- You receive data step by step
Example with Button Click
function add(a) {
return function(b) {
return a + b;
};
}
let out = add(10); // first value fixed
function watchOutput(b) {
console.log(out(b));
}
<button onclick="watchOutput(20)">Click</button>
Output:
30
Explanation:
- First value (
10) is stored - Second value (
20) comes later (on click)
Real-World Example (Logging System)
function logs(level) {
return function(msg) {
return "Level: " + level + ", Message: " + msg;
};
}
console.log(logs("INFO")("User logged in successfully"));
Output:
Level: INFO, Message: User logged in successfully
Why this is useful:
- You fix the log level first
- Then reuse it for multiple messages
Benefits of Function Currying
1. Reusability
You can reuse partially applied functions
const add10 = add(10);
console.log(add10(5)); // 15
console.log(add10(20)); // 30
2. Cleaner Code
Break complex functions into smaller steps
3. Partial Application
Useful when data comes in stages
4. Used in Libraries
Popular libraries using currying:
- Lodash
- Ramda
- Redux (functional patterns)