What is the currying function in JavaScript?

JavascriptWeb DevelopmentFront End Technology

Currying is a technique in functional programming that performs the transformation of a function with multiple arguments into several functions containing a single argument in a sequence.

The translation of a function happens something like this

function dummy(param1, param2, param3, .....) {
}

is converted into -

function curriedFunction(param1) {
   return function (param2) {
      return function (param3) {
      }
   }
}

In the curried function, we simply wrap a function inside a function. It means the return of a function is processed by the above function to obtain this kind of translation. The parent function takes the first provided argument that returns the function taking the next argument. This keeps on repeating until the number of arguments ends. Hopefully, the function that receives the last argument returns the expected result.

The curried name is used by the American Mathematician name Huskel Curry who developed this technique.

Example 1

In the below example, we are finding the volume of a box containing 3 variables i.e. length, breadth, and height. The function is called consequently with the parameters that provide arguments and return the appropriate result.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>CapsLock Detecter</title>
</head>
<body>
   <h1 style="color: red;">Welcome To Tutorials Point</h1>
   <script type="text/javascript">
      function calculateVolume(length, breadth, height) {
         return length * breadth * height;
      }
      console.log("Volume of the container is: " +calculateVolume(4,5,6));
   </script>
</body>
</html>

Output

It will produce the following output in the console.

Volume of the container is: 120

Example 2

In the below example, we are going to convert the above function into a curried function and then pass the required variables to it. On passing the variables, we can see that both the function returns the same output as it should be.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>CapsLock Detecter</title>
</head>
<body>
   <h1 style="color: red;">Welcome To Tutorials Point</h1>
   <script type="text/javascript">
      function calculateVolume(length) {
         return function (breadth) {
            return function (height) {
               return length * breadth * height;
            }
         }
      }
      console.log("Volume of the container is:" + calculateVolume(4)(5)(6));
   </script>
</body>
</html>

Output

It will produce the following output in the console

Volume of the container is: 120
raja
Updated on 28-Apr-2022 13:56:33

Advertisements