Currying in JavaScript
Tags: javascript, functional, beginners, webdev
Published: 2020-07-08 19:40:22

<!-- wp:paragraph -->
<p>Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That is, when we turn a function call <code>sum(1,2,3)</code> into <code>sum(1)(2)(3)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The number of arguments a function takes is also called <code>arity</code>.</p>
<!-- /wp:paragraph -->

```javascript
function sum(a, b) {
    // do something
}
function _sum(a, b, c) {
    // do something
}
```

<!-- wp:paragraph -->
<p>function <code>sum</code> takes two arguments (2-arity function) and <code>_sum</code> takes three arguments (3-arity function).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Curried functions are constructed by chaining closures by defining and immediately returning their inner functions simultaneously.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Why it’s useful ?</h3>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>Currying helps we avoid passing the same variable again and again.</li><li>It helps to create a higher order function</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Example:</p>
<!-- /wp:paragraph -->

```javascript
function sum(a, b, c) {
    return a + b + c;
}
```

```javascript
sum(1,2,3); // 6
```
<!-- wp:paragraph -->
<p>As we see, function with the full arguments. Let’s create a curried version of the function and see how we would call the same function (and get the same result) in a series of calls:</p>
<!-- /wp:paragraph -->

```javascript
function sum(a) {
    return (b) => {
        return (c) => {
            return a + b + c
        }
    }
}

console.log(sum(1)(2)(3)) // 6
```

<!-- wp:paragraph -->
<p>We could separate this sum(1)(2)(3) to understand it better:</p>
<!-- /wp:paragraph -->

```javascript
const sum1 = sum(1);
const sum2 = sum1(2);
const result = sum2(3);
console.log(result); // 6
```

<!-- wp:paragraph -->
<p>Let's get to know how it works:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We passed 1 to the <code>sum</code> function:</p>
<!-- /wp:paragraph -->

```javascript
let sum1 = sum(1);
```

<!-- wp:paragraph -->
<p>It returns the function:</p>
<!-- /wp:paragraph -->

```javascript
return (b) => {
        return (c) => {
            return a + b + c
        }
}
```

<!-- wp:paragraph -->
<p>Now,&nbsp;<code>sum1</code>&nbsp;holds the above function definition which takes an argument&nbsp;<code>b</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We called the&nbsp;<code>sum1</code>&nbsp;function, passing in&nbsp;<code>2</code>:</p>
<!-- /wp:paragraph -->

```javascript
let sum2 = sum1(2);
```

<!-- wp:paragraph -->
<p>The <code>sum1</code> will return the third function:</p>
<!-- /wp:paragraph -->

```javascript
return (c) => {
            return a + b + c
}
```

<!-- wp:paragraph -->
<p>The returned function is now stored in <code>sum2</code> variable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>sum2</code> will be:</p>
<!-- /wp:paragraph -->

```javascript
sum2 = (c) => {
            return a + b + c
}
```

<!-- wp:paragraph -->
<p>When <code>sum2</code> is called with 3 as the parameter,</p>
<!-- /wp:paragraph -->

```javascript
const result = sum2(3);
```

<!-- wp:paragraph -->
<p>it does the calculation with the previously passed in parameters: a = 1, b = 2 and returns 6.</p>
<!-- /wp:paragraph -->

```javascript
console.log(result); // 6
```

<!-- wp:paragraph -->
<p>The last function only accepts <code>c</code> variable but will perform the operation with other variables whose enclosing function scope has long since returned. It works nonetheless because of <code>Closure</code> 🔥</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Currying &amp; Partial application 🤔</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Some might start to think that the number of nested functions a curried function has depends on the number of arguments it receives. Yes, that makes it a curry.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take same <code>sum</code> example:</p>
<!-- /wp:paragraph -->

```javascript
function sum(a) {
    return (b, c) => {
        return a * b * c
    }
}
```

<!-- wp:paragraph -->
<p>It can be called like this:</p>
<!-- /wp:paragraph -->

```javascript
let x = sum(10);
x(3,12);
x(20,12);
x(20,13);

// OR

sum(10)(3,12);
sum(10)(20,12);
sum(10)(20,13);
```

<!-- wp:paragraph -->
<p>Above function expects 3 arguments and has 2 nested functions, unlike our previous version that expects 3 arguments and has 3nesting functions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>This version isn’t a curry.</strong> We just did a partial application of the <code>sum</code> function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Currying and Partial Application are related (because of closure), but they are of different concepts.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Partial application transforms a function into another function with smaller arity.</p>
<!-- /wp:paragraph -->

```javascript
function sum1(x, y, z) {
    return sum2(x,y,z)
}

// to

function sum1(x) {
    return (y,z) => {
        return sum2(x,y,z)
    }
}
```

<!-- wp:paragraph -->
<p>For Currying, it would be like this:</p>
<!-- /wp:paragraph -->

```javascript
function sum1(x) {
    return (y) = > {
        return (z) = > {
            return sum2(x,y,z)
        }
    }
}
```

<!-- wp:paragraph -->
<p><strong>Currying</strong> creates nesting functions according to the number of the arguments of the function. Each function receives an argument. If there is no argument there is no currying.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To develop a function that takes a function and returns a curried function:</p>
<!-- /wp:paragraph -->

```javascript
function currying(fn, ...args) {
    return (..._arg) => {
        return fn(...args, ..._arg);
    }
}
```

<!-- wp:paragraph -->
<p>The above function accepts a function (fn) that we want to curry and a variable number of parameters(…args). The rest operator is used to gather the number of parameters after fn into ...args.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, we return a function that also collects the rest of the parameters as …_args. This function invokes the original function fn passing in ...args and ..._args through the use of the spread operator as parameters, then, the value is returned to the user.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, we can use the above function to create curry function.</p>
<!-- /wp:paragraph -->

```javascript
function sum(a,b,c) {
    return a + b + c
}

let add = currying(sum,10);
add(20,90); // 120
add(70,60); // 140
```

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Closure makes currying possible in JavaScript. I hope you have learned something new about currying!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Thanks for reading this article&nbsp;♥️</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;If you have any question, please feel free to ping me on&nbsp;<strong><a href="https://twitter.com/suprabhasupi">@suprabhasupi</a> 😋</strong></p>
<!-- /wp:paragraph -->

<table>
  <tbody>
    <tr>
      <td>
        🌟 <a href="https://twitter.com/suprabhasupi"> Twitter</a>
      </td>
      <td>
        👩🏻‍💻 <a href="https://www.suprabha.me/"> Suprabha.me</a>
      </td>
<td>
        🌟 <a href="https://www.instagram.com/suprabhasupi/"> Instagram</a>
      </td>
    </tr>
  </tbody>
</table>