Definition: Currying is a technique in JavaScript where a function does not take all arguments at once.
- Instead, it takes one argument at a time and returns a new function until all arguments are provided.
-
It transforms:
f(a, b, c)into
f(a)(b)(c)
🔹 Why Use Currying?
- Reusability → create specialized functions from general ones.
- Cleaner code for repetitive operations.
- Helps in functional programming and composing functions.
🔹 Example 1: Normal Function vs Curried Function
✅ Normal Function
function add(a, b, c) {
return a + b + c;
}
console.log(add(2, 3, 4)); // 9
✅ Curried Function
function add(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
console.log(add(2)(3)(4)); // 9
🔹 Example 2: Using Arrow Functions (Shorter Syntax)
const add = (a) => (b) => (c) => a + b + c;
console.log(add(5)(10)(15)); // 30
🔹 Example 3: Practical Use Case (Reusable Logging)
function log(level) {
return function(message) {
console.log(`[${level}] ${message}`);
};
}
const info = log("INFO");
const error = log("ERROR");
info("Server started"); // [INFO] Server started
error("Database failed"); // [ERROR] Database failed
🔹 Key Takeaways
- Currying = breaking a function with multiple args into nested functions taking one arg each.
- Helps in code reuse and functional programming.
- Commonly used in libraries like Lodash and functional patterns in React/Redux.