Open In App

What is Function Currying in JavaScript ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Original function with multiple arguments
function add(x, y) {
  return x + y;
}
 
// Curried version of the add function
function curriedAdd(x) {
  return function(y) {
    return x + y;
  };
}
 
// Using the curried function
const add5 = curriedAdd(5);
console.log(add5(3)); // Outputs: 8


Output

8

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads