JavaScript WordBook

Providing simple explanations for seemingly complex development terms

Currying

Currying is creating a function that takes multiple arguments individually.


Currying is a concept of functional programming that uses closures to allow a function to take its arguments one by one.

A curried function will return another function each time it’s invoked, until finally returning the result once all arguments have been provided. 

To make this clearer, let's start with a simple multiplication function. This function that multiple arguments and simply multiplies them returning the resulting number.

// Javascript
const multiplyBy = (a,b) => a * b;

// Returns 25
multiplyBy(5,5);

Now if we wanted to write this as a curried function we would change it to accept its arguments one at a time, for example: 

// Javascript
const multiplyBy = a => b => a * b;

// Returns 25
multiplyBy(5)(5);

You can see this now takes each argument individually. 

Another way to write this would be so that it takes its arguments returning a functioning to take any missing arguments. This then allows the function to be executed in either of the above methods, for example: 

// Javascript
const multiplyBy = (a, b) => {
  if (b === undefined) {
    return b => a * b;
  }

  return a * b;
}

// Returns 25
multiplyBy(5,5);

// Returns 25
multiplyBy(5)(5);

This can be useful, for example allowing a base function to be used for multiple purposes. In our case this could be using our base multiplyBy function to create further functions that handle specific multipliers.

// Javascript
const multiplyBy = (a, b) => {
  if (b === undefined) {
    return b => a * b;
  }
  
  return a * b;
}

const multiplyBy5 = multiplyBy(5);
const multiplyBy6 = multiplyBy(6);

// Returns 25
multiplyBy5(5);

// Returns 30
multiplyBy6(5);

When using curried functions be careful not to create convoluted code that ends up difficult for other developers to understand.