What is Function Currying in JavaScript ?
Last Updated :
30 Jan, 2024
Function currying is a concept in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. The result of each function is a new function that expects the next argument in the sequence until all arguments have been provided, and finally, the original function is invoked with all the arguments.
Function currying has several benefits:
- Partial Application: It allows you to partially apply arguments to a function, creating new functions with predefined parameters. This can be useful for creating reusable function templates or for creating specialized versions of functions.
- Flexibility: Curried functions provide flexibility in function composition and can be easily combined with other functions.
- Readability: Currying can improve the readability of code by breaking down complex functions into smaller, more manageable pieces.
- Memoization: Curried functions can be easily memorized, which can improve performance by caching the results of expensive function calls.
Example: Here, the curriedAdd
function transforms the original add
function into a curried version. When curriedAdd(5)
is called, it returns a new function that expects one argument (y
). This new function adds 5
to whatever value is passed as y
.
Javascript
function add(x, y) {
return x + y;
}
function curriedAdd(x) {
return function (y) {
return x + y;
};
}
const add5 = curriedAdd(5);
console.log(add5(3));
|
Share your thoughts in the comments
Please Login to comment...