Defination: Currying in JavaScript is a functional programming technique where a function is transformed into a sequence of functions, each taking one argument at a time. Instead of passing all arguments at once, currying allows partial application, making functions more reusable and composable.
Code Example:
function multiply(a) {
return function (b) {
return a * b;
};
}
const multiplyBy5 = multiply(5); // First function call stores `5`
console.log(multiplyBy5(2)); // Output: 10
console.log(multiplyBy5(4)); // Output: 20
Here, returns a function that "remembers" , allowing us to reuse it.
Benefits of Currying
✔ Reusability: Functions can be preset and reused with different arguments.
✔ Function Composition: Helps in creating small, modular functions for clean code.
✔ Enhancing Readability: Makes complex operations easier to understand.
Real World use cases of currying in js:
Currying is a powerful technique in JavaScript, especially in functional programming, where it helps create reusable, composable, and modular functions. Here are some real-world use cases where currying is highly beneficial
🔹 1. Event Handling in JavaScript & React
In event listeners or React components, currying allows you to pass predefined arguments while handling events dynamically.
Code Example:
const handleClick = (message) => (event) => {
console.log(`${message}, clicked on ${event.target.id}`);
};
document.getElementById("myButton").addEventListener("click", handleClick("Hello"));
✅ Benefit: Reduces repeated function definitions while handling user interactions.
🔹 2. URL Builder for API Calls
Currying makes API request generation cleaner and modular.
Code Example:
const buildURL = (baseURL) => (endpoint) => (queryParams) =>
`${baseURL}/${endpoint}?${new URLSearchParams(queryParams)}`;
const getUserData = buildURL("https://api.example.com")("users");
console.log(getUserData({ id: 123 }));
// Output: https://api.example.com/users?id=123
✅ Benefit: Allows dynamic endpoint creation without duplicating code.
🔹 3. Logging Utility with Different Level
Currying simplifies logging functions by setting predefined log levels.
Code Example:
const logMessage = (level) => (message) => console.log(`[${level}]: ${message}`);
const infoLog = logMessage("INFO");
const errorLog = logMessage("ERROR");
infoLog("System is running smoothly"); // Output: [INFO]: System is running smoothly
errorLog("Something went wrong!"); // Output: [ERROR]: Something went wrong!
✅ Benefit: Ensures consistent logging structure while avoiding unnecessary repetitions.
🔹 4. Validating Form Inputs Dynamically
Currying allows flexible validation functions for forms
Code Example:
const validateLength = (minLength) => (input) => input.length >= minLength;
const isValidUsername = validateLength(5);
console.log(isValidUsername("Shravan")); // Output: true
console.log(isValidUsername("UI")); // Output: false
✅ Benefit: Creates reusable validation functions for different input fields.
🔹 5. Styling Components Dynamically
In UI frameworks like React, currying helps manage dynamic styles.
Code Example:
const applyStyles = (fontSize) => (color) => ({
fontSize: `${fontSize}px`,
color: color,
});
const headingStyle = applyStyles(24)("blue");
console.log(headingStyle); // Output: { fontSize: "24px", color: "blue" }
✅ Benefit: Improves code maintainability and ensures dynamic styling
🔹 6. Partial Function Application for Discounts
In e-commerce apps, currying enables efficient discount calculations.
Code Example:
const calculateDiscount = (discount) => (price) => price - price * discount;
const apply10Percent = calculateDiscount(0.10);
console.log(apply10Percent(100)); // Output: 90
console.log(apply10Percent(200)); // Output: 180
✅ Benefit: Presets discount logic for different scenarios
Final Thoughts
Currying makes JavaScript functions more reusable, modular, and efficient, perfect for React, API calls, event handling, validation, logging, styling, and more.
No comments:
Post a Comment