Understanding currying in JavaScript

Currying is a technique which is very important in functional programming. It is not only used in JavaScript but used in other languages as well. Currying is a technique that applies a function to its arguments one at a time, with each application returning a new function that accepts the next argument.

Let us see how currying can be done in JavaScript.

The idea behind currying is to take a function,

function add(x, y) { return x + y; }

and transform the function so that it takes single argument and returns a function which performs the required operation.

function curriedAdd(x) {
  return function(y) { return x + y; }
}

This curried adder function can then be used in creating a special adder function like curriedAdd(3), which adds 3 to every subsequent call which is made using this function.

let add3 = curriedAdd(3)

console.log(add3(4))//7

Here, the curriedAdd(3) creates another function which is stored in add3. When add3 is called with any number, here 4 it returns the sum of that number with 3. That is 7 is obtained as output.

There is an other definition for currying, Currying refers to partially evaluating a problem and using the solution of the evaluated part in subsequent functions to get the result fast / using the function to make another function.

Imagine our curried function looked like this:

let doTheHardStuff = function(x) {
  let z = doSomethingComputationallyExpensive(x)
  return function (y){
    z + y
  }
}

We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)

Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things.

  1. cache expensive operations

  2. achieve abstractions in the functional paradigm.

Now let us look as some of the examples which can be done using currying.

Example 1

add(1)(2)(3)//must return 6

Think about how you can make a curry function for the above question before looking at the answer.

Answer

function add(a){
 return function(b){
  return function(c){
   return a+b+c  }}}

This can also be written as an arrow function to make it easy to read,

let add = (a) => (b) => (c) => a+b+c

Example 2

Let us look at an extension of the above question,

add(1)(2)(3)…(n)()

This function adds all the argument until it encounters an empty call.

Answer

function add(a) {
  return function(b){
    if(b){
      return add(a+b)
    }
    return a
  }
}

const add = (a) => (b) => b ? add(a+b) : a

Here are the resources I used to understand currying, have a look through them to understand better.

Happy Coding!

If you enjoyed and learned from this article, I will like to connect with you. Connect with me on LinkedIn to be part of my journey.