What is currying in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Currying

Currying is a technique of evaluating function with multiple arguments, into sequence of functions with single argument.In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.

Uses of currying function

  a) It helps to avoid passing same variable again and again.

  b) It is extremely useful in event handling. 

syntax:

     function Myfunction(a) {
        return (b) => {
           return (c) => {
             return a * b * c
             }
            }
         }

Example 

In the following example,since no currying is used, all the parameters were passed at once(volume(11,2,3))  to the existing function to calculate the volume.

 Live Demo

<html>
<body>
<script>
   function volume(length, width, height) {
      return length * width * height;
   }
   document.write((volume(11,2,3)));
</script>
</body>
</html>

Output

66

Example

In the following example,since currying is used,parameters were passed one by one(volume(11)(2)(3))  until the last function called the last parameter .

 Live Demo

<html>
<body>
<script>
   function volume(length) {
      return function(width) {
         return function(height) {
            return height * width * length;
         }
      }
   }
document.write(volume(11)(2)(3))
</script>
</body>
</html>

Output

66
raja
Published on 30-May-2019 11:08:32
Advertisements