
Have you ever come across functions that return other functions?
Ever wondered how you could pre-fill some arguments of a function and reuse it later?
This is where a powerful functional programming concept, Currying, comes into play.
By the end of this article, you will have a solid understanding of what currying is, why we use it, and how it works.
Currying is the transformation of a function that takes multiple arguments into a sequence of nested functions, each of which takes a single argument.
In simple terms, instead of calling a function with all its arguments at once, you call a series of functions one after the other, each supplying one argument.
Let's look at a practical example. Imagine we want to create a function to send an automated email. Instead of having one function that takes to, subject, and body all at once, we can curry it.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Currying</title>
  </head>
  <body>
    <script>
      function sendAutomatedEmail(to) {
        return function (subject) {
          return function (body) {
            console.log(
              `Sending email to ${to} with subject "${subject}" and body "${body}"`
            );
          };
        };
      }
      sendAutomatedEmail("example@example.com")("Hello World")(
        "This is a test email."
      );
    </script>
  </body>
</html>
In the code above, sendAutomatedEmail is a curried function. Each function in the sequence accepts a single argument and returns the next function in the chain until the last function, which performs the final action.
Currying is a powerful technique with several benefits. The two main reasons for its use are partial application and function composition.
Partial application is the process of creating a new function by pre-filling some of the arguments of an existing function. Currying makes this incredibly easy.
For example, using our sendAutomatedEmail function, we could create a new function for a specific recipient:
const sendEmailToUser = sendAutomatedEmail("user@example.com");
Now, sendEmailToUser is a new function that only needs subject and body. This makes our code more reusable and less repetitive.
Currying also simplifies function composition, which is the act of combining multiple functions to create a new one. By ensuring each function takes and returns a single value, curried functions can be chained together easily.
Currying is a functional programming concept that transforms a function with multiple arguments into a sequence of nested functions, each taking a single argument. It's a key technique for partial application, which allows you to create specialized, reusable functions, and for function composition, which helps you chain functions together. By embracing currying, you can write more modular and expressive code.