Currying VS Partial Application in JavaScript.


Currying − In currying a function takes another function and some arguments. The function then returns one function with one parameter only. It returns the function with one argument which can be chained together.

Partial application − In partial application some of the arguments can be bind to some values to produce a function with less arguments.

Following is the code for currying vs partial application in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Currying vs Partial application in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see currying and partial application example</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function multiply(x, y) {
      return function (y) {
         return x * y;
      };
   }
   function add(a, b, c, d) {
      return a + b + c + d;
   }
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      "Currying<br>multiply(2)(5) = " + multiply(2)(5) + "<br>";
      let partialAdd = add.bind(this, 2, 3);
      resEle.innerHTML +=
      "Partial Application <br> partialAdd(4,5) = " +
      partialAdd(4, 5) +
      "<br>";
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


Updated on: 22-Jul-2020

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements