![]() |
Currying is an advanced but very useful technique in functional programming. In JavaScript, it allows you to transform a function that accepts multiple arguments into a sequence of functions that accept only one argument at a time. Let's see together what it means, why it can be useful, and how to implement it.
๐ What is currying?
Currying is a technique that transforms a function that takes multiple parameters into a series of functions, each of which takes a single parameter.
In other words, instead of calling a function passing all the parameters together, we call it one at a time, returning intermediate functions that wait for the next parameter.
Classic function (non-curried)
function sum(a, b) {
return a + b;
}
console.log(sum(2, 3)); // 5
Same function, rewritten with currying
function sumCurried(a) {
return function(b) {
return a + b;
};
}
console.log(sumCurried(2)(3)); // 5
As you can see:
sommaCurried(2)
returns a function that expects the second parameterb
.- Calling this function immediately with
(3)
gives us the result.
✅ Why use currying?
Curriing allows you to "precompile" some parts of a function, creating new, more specific and reusable functions.
This is very useful when:
- You want to create "custom" versions of generic functions.
- You want to avoid repeating fixed values in multiple places in your code.
- You want to write more modular code and Clean.
Benefits:
-
Reusability: You can create specialized versions of functions.
-
Composition: Integrates well with other functional functions.
-
Clarity: Promotes more readable and modular writing.
✖️ When NOT to use it
While currying is powerful, it's not always necessary. Avoid it when:
-
The code becomes less readable.
-
The number of parameters varies frequently.
-
The function is very simple and used only once.
๐งช 5 concrete examples of currying in action
1. Personalize Messages with Partial Functions
function createMessage(type) {
return function(username) {
if (type === "welcome") {
return "Hello " + username + ", welcome!";
} else if (type === "error") {
return "Hello " + username +", an error occurred.";
} else {
return "Hello " + UserName + "!";
}
};
}
const WelcomeMessage = createMessage("welcome");
const ErrorMessage = createMessage("error");
console.log(WelcomeMessage("Luca")); // Hi Luca, welcome!
console.log(ErrorMessage("Anna")); // Hi Anna, an error occurred.
Use currying to create specific messages that can be reused across multiple parts of your code.
2. Configuring functions to send emails
function inviaEmail(sender) {
return function(recipient, message) {
return `From: ${sender}\nTo: ${recipient}\nMessage: ${message}`;
};
}
const emailFromMario = inviaEmail("mario@example.com");
console.log(emailFromMario("anna@example.com", "Hi Anna, how are you?"));
This way, you can easily create preconfigured functions for different senders.
3. Calculate Discount Prices
function calculateDiscountPrice(percentageDiscount) {
return function(price) {
return price - (price * PercentageDiscount / 100);
};
}
const discount10 = calculateDiscountPrice(10);
const discount20 = calculateDiscountPrice(20);
console.log(discount10(100)); // 90
console.log(discount20(100)); // 80
You can create specialized functions for each type of discount to use clearly and easily.
4. Preparing HTTP requests with fixed parameters
function creaRequest(urlBase) {
return function(endpoint, method) {
return `Send request ${method} to ${urlBase}${endpoint}`;
};
}
const apiItalia = creaRequest("https://api.italia.it/");
console.log(apiItalia("weather", "GET")); // Send GET request to https://api.italia.it/weather
console.log(apiItalia("traffic", "POST")); // Send POST request to https://api.italia.it/traffic
Currying allows you to configure parameters like the URL base in advance.
5. Manage user permissions
function checkPermission(role) {
return function(action) {
const permissions = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"]
};
return permissions[role] && permissions[role].includes(action);
};
}
const adminHasPermission = checkPermission("admin");
const guestHasPermission = checkPermission("guest");
console.log(adminHasPermission("delete")); // true
console.log(guestHasPermission("write")); // false
Clear and modular functions for checking permissions without duplicating code.
๐ฏ Conclusion
Currying is a simple yet powerful technique for writing clearer, more modular, and reusable JavaScript code.
It allows you to pre-set some of a function's parameters, creating new, customized functions for your use cases.
Follow me #techelopment
Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment