What is a Currying function?

Tomasz Włodarczyk
tomaszwlodarczyk
Published in
2 min readSep 16, 2020

--

Currying function is a basic tool in functional programming.
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.

Let’s see a simple example. We’ll create a function ‘add’, which has three arguments and will return the sum of all arguments.

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

add(1, 2, 3);

In above, we see a function with three arguments if we would like to change the numeric arguments we need to write a new function because:

  • This function expects only three arguments
  • It is considered good practice to write functions with a minimal amount of arguments
  • We can’t call function add with two parameters or more than three parameters.

If we want the function to be more flexible. We could use the currying function.

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

add(1)(2)(3); // 6

We used Currying functions:) It’s simple, right?

Now, We want to write a function, which is more flexible. It will be a function which will not have specific arguments but return the sum of all arguments. We’ll use currying functions, of course.

function add(a) {
let sum = a;

const addSum = (b) => {
sum = sum + b;

return addSum ;
}

addSum .result = () => sum ;

return addSum ;
};

console.log('result ', add(2)(4).result()); // 6
console.log('result ', add(2)(4)(6).result()); // 12
console.log('result ', add(2)(4)(6)(9).result()); // 21

In the above snippet, We see a function ‘add’ with one parameter. This parameter assigns to variable ‘sum’. Variable sum will be the total sum of all parameters. According to the logic of the currying function we created another function ‘addSum’ with arguments ‘b’. This function adds the current sum to value b and returns itself.

Call function add with parameters

The completed ‘add property’ result. This property displays the result of the sum.

When and Why use Currying?

Currying using when we want to have pre-configured behave our program. Also helps us avoid often call function with same parameter. Example:

function add(2) {
return function (b) {
return 2 + b;
}
}

More advance examples find here. Currying can seems difficult but I hope that explained what is currying and you will not be have problem with Currying functions in JavaScript.

--

--