## DEV Community is a community of 670,881 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. # JavaScript Currying Currying in JavaScript Suprabha
🔥 New JS, CSS, HTML articles every week 🔥 Frontend engineer @gojekindonesia 👩🏻‍💻 http://instagram.com/suprabhasupi

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.

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.

That is, when we turn a function call `sum(1,2,3)` into `sum(1)(2)(3)`

The number of arguments a function takes is also called `arity`.

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

function `sum` takes two arguments (2-arity function) and `_sum` takes three arguments (3-arity function).

Curried functions are constructed by chaining closures by defining and immediately returning their inner functions simultaneously.

### Why it’s useful ?

1. Currying helps we avoid passing the same variable again and again.
2. It helps to create a higher order function

Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.

Example:

``````function sum(a, b, c) {
return a + b + c;
}
``````
``````sum(1,2,3); // 6
``````

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:

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

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

We could separate this sum(1)(2)(3) to understand it better:

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

Let's get to know how it works:

We passed 1 to the `sum` function:

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

It returns the function:

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

Now, `sum1` holds the above function definition which takes an argument `b`.

We called the `sum1` function, passing in `2`:

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

The `sum1` will return the third function:

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

The returned function is now stored in `sum2` variable.

`sum2` will be:

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

When `sum2` is called with 3 as the parameter,

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

it does the calculation with the previously passed in parameters: a = 1, b = 2 and returns 6.

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

The last function only accepts `c` variable but will perform the operation with other variables whose enclosing function scope has long since returned. It works nonetheless because of `Closure` 🔥

## Currying & Partial application 🤔

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.

Let's take same `sum` example:

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

It can be called like this:

``````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);
``````

Above function expects 3 arguments and has 2 nested functions, unlike our previous version that expects 3 arguments and has 3nesting functions.

This version isn’t a curry. We just did a partial application of the `sum` function.

Currying and Partial Application are related (because of closure), but they are of different concepts.

Partial application transforms a function into another function with smaller arity.

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

// to

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

For Currying, it would be like this:

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

Currying 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.

To develop a function that takes a function and returns a curried function:

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

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.

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.

Now, we can use the above function to create curry function.

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

``````

Closure makes currying possible in JavaScript. I hope you have learned something new about currying!

If you have any question, please feel free to ping me on @suprabhasupi 😋

 🌟 Twitter 👩🏻‍💻 Suprabha.me 🌟 Instagram

## Discussion (28) John Peters

Thanks for excellent simple explanation. However I must admit I see no valid reason for this pattern. It hides outcomes based on parameter counts, but later remembers prior values? It's like a dynamic function with pre determined state. What would the test pattern look like? David • Edited

This is a fair thought and/or assumption. I think the OP’s post is illuminating more so how it is done rather than how or why it could be useful or valuable. It would confuse the unacquainted if presented in a code based with those unfamiliar with the functional paradigm, too.

However, the value that I see in currying and partial application is composition — yeah... instead of writing an addTwo, addThree, addFour, addFive. It can simply be composed of a curried function. We use composition all the time by trying to perform code-reuse. Currying and partial application is just another tool or enabler and very standard in more purely functional languages — as we begin to think how we can make something with a sum of parts rather than building that something from scratch over and over again. If you’ve ever used underscore or the lodash libraries, Lodash declares its parameters in a very particular order to support this whereas underscore, unfortunately, does not. I’m on my phone so I cannot show the adder examples with code snippets but they can easily be found online.

Testing is simple — similarly to any unit test where we test what the expected behavior should be and they are: with no arguments supplied, some arguments supplied, and all arguments supplied and assert those outcomes David • Edited

I'm not sure that I follow your example... if you've a function that reads `sum`, you expect it to produce a "sum". Right?

State is only relevant if it's mutable. If you supply an object with mutable state to a partially applied function, we're in for a debugging nightmare. I would even go so far as to say it's one of the reasons functional ideas have lackluster adoption in JS, unless we're dealing with scalar values or objects with immutable state.

Let's say that we have a function that helps us compute the size of a park plus some "buffer" that is only supplied at the time of construction, but we don't yet know before hand. We want to maintain a very specific interface: courts are supplied somewhere early in the process, but we expose to the builder only one parameter -- the buffer. They need not worry about courts and sizes, it is done somewhere earlier and up the chain.

``````function parkSize(courts) {
return function(buffer) {
return sum(courts) + buffer;
}
}
``````

My example isn't very hard to test is it? The set-up involves two steps:

1. supply court objects
2. supply a buffer
3. make an assertion

With the contrived example I have. I can "compose" a new function that exposes a "limited" and easy to understand interface for someone that needs to determine "recreational areas":

``````var courts = [...];
var parkArea = parkSize(courts);
var buffer = 100;
function recreationalSpace(buffer, privateSpace) {
return sum(parkArea(buffer)) - privateSpace;
}
``````

This is no different than you using a library that's pre-configured -- you don't need to know all the default values before using it; one can infer based on the interface that's exposed. Otherwise, we could push for writing procedural imperative code that's all in a single file. How testable would that be?

Currying and partial application allow the designer/developer to control when arguments are supplied, otherwise you could end up having an outsized parameter list which forces the consumer of the function to know about the entire world at point of conception (runtime). The consumer of the function need not know about everything that was configured/supplied before it. Just like you don't need to know about all the internals of the library before you can use it. The only thing that should be implicit is the name of your function and what it's trying to convey... in the context of OOP, we this idea captured as well, called "encapsulation" -- prevent direct access to data except through a predetermined interface (methods). We don't want abstraction leaks and data access from everywhere. The consumer should need not know about the implementation details.

Every function that I've declared should be tested, so that if something is odd (like a bug), I know immediately where to look and what assumptions were made. It's really no different from us using a library that's hopefully well tested. We build tests upon a combination or composition of our own assumptions about what a library provides for us. In fact some of the libraries people use in JavaScript have functions that are exposed that are partially applied. You never need to dig into them unless seemingly unexpected behavior is exhibited after checking our own code... John Peters • Edited

Thanks David I did some debugging today to figure this out.

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

let mysum = sum(1);
debugger;
let mysum2 = mysum(2, 3);
debugger;
``````

The results were: As we can see, if a debugger wanted to know the value of mysum, in the console, they would only see it's a function as shown on far right side.

There's zero indication that this function when executed the 2nd time, has a preset value of 1 in it.

Now assume that mysum was set on entry to a module, but mysum2 was set much later. The developer is now wondering how mysum2 = 6...

mysum and mysum2 give no answers, but creating a de-composed form as shown in mysum3 kind-of, sort-of does help the debugger to understand. This is what I was struggling with and why I mentioned an implicit state..

mysum is not a value, it's a function pointer! No values are returned until the 2nd and 3rd parameters are passed in. So this shows us that returning multiple functions forces a bit of thinking differently, as was said earlier it's composition of functions. Expressed in this syntax most clearly

``````let mysum3 = sum(1)(2,3);
``````

Indeed anonymous functions at that! I've seen this syntax before; but until now, didn't fully understand it.

Thanks! David • Edited

Ah! I love that your curiosity made you do a deeper dive! I went through something similar in other languages and honestly have never done currying or partial application in JS, although I've wanted to when I was spending most of my time in it.

Implicit state is always there, when you're working with a function that has had some arguments partially applied "earlier on". Does it make debugging more difficult? Yeah, it's not as easy as just shoving a break-point and inspecting current state. In languages, like Haskell, the lazy-evaluation becomes a challenge but yields performance gains. I work in Elixir which has nice facilities for this type of introspection, because it allows one to perform eager or lazy evaluation (`Enum` vs `Stream`) with the same functions in both modules

But I guess you're right, though -- that this idea (currying and partial application) isn't that useful in JS because it isn't the default paradigm that most of us are operating in. If employed, it would be analogous to using regexes everywhere and having to constantly explain them to everyone else. I very much like the ideas behind "functional reactive programming" ala RxJS where everything is a stream enabling some really really neat things one can do, but it is tough to get organizational buy-in when outside of some skunk-works team or small shop. But it is a powerful tool to maximize code reuse and a composition enabler in other languages and paradigms though jesuscovam

I think the same, but It could be useful for when a param must be computed from other functions, that you might already wrote outside the currying, sor I just my use like this currying(1)(resultOf(2))(3). That's my take in my head. John Peters • Edited

Nice, this makes for placeholder to inject the results of functions.

However, we are also able to do this:

``````someFunction(1, get2ndParm(), 3);  Which is shorter.
``````

Also, wouldn't currying break the pure function pattern? Pragmatic Maciej

Currying is not pattern. It is function property. In all FP languages functions are like that, so they are curried.

If you have function f: a ->b->c then by applying only a we have function g: b->c.

In JS as it's not FP language we need to make currying manually by using closures and returning function from function. It doesn't violate any purity as it is exactly FP concept. Pragmatic Maciej

If it would not have value it would not exists. It has huge value. But this answer would be worth a whole post about that ;) jesuscovam

maybe the second function would need a valued computed from the first function, so it could be use as a pipeline of computed values that are reusable and can be rearranged as legos John Peters

Just wondering how is that better than this?

``````const add(a,b)=>a+b;
``````

The decomposition of earlier example reveals a simpler understanding until one understands compositional parameter injection. It's better if you want to use functions which have a uniform interface of transforming a single input value to a single output value.

Consider using map like so

Using the binary form of add you would need to introduce an ad hoc function to rectify the interface

[1, 2, 3.map(v => add(3, v))

The one to one mapping style generally makes composition simpler.

So, the question is, do you want to do that kind of stuff? Iven Marquardt • Edited

This is not partial application in its imperative meaning:

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

sum(1);
``````

It is a curried function that returns a multi-argument one.

Partial application is a dynamic concept of imperative programming. Here is a possible approach:

``````const partial = (f, ...args) => (...args_) =>
f(...args, ...args_);

const sum = (a, b, c) =>
a * b * c;

partial(sum, 1) (2, 3); // 6
`````` Pragmatic Maciej

How partial application have any imperative meaning? Partial application is just possibility of applying to function less arguments than function defines. If function is curried then partial application is just using this function property. Pankaj Sharma

Hey @Suprabha, thank you for this article. I just want to know in real-world why we need currying and where I should use currying. 🤔 As a developer, I would like to know the kind of problems you solve with currying.🤓🧐

Again Thank you... Functional Javascript

I make heavy use of currying with functional pipelines.

Here's an example of comparing a function pipeline with method chaining from a recent tweet. #### src

the filterNotStartsWith and replaceByRegex funcs are curried (they are funcs that return funcs)

Here are their implementations....

``````/**
@func
from the supplied arr,

@param {string} chunk
@return {(a: string[]) => string[]}
*/
export const filterStartsWith = chunk => a => fil(s => s.startsWith(chunk), a);

/**
@func
replace a substring with another substring in a haystack of text

@param {RegExp} n needleRegex
@param {string} r replacement
@return {(h: string) => string} - haystack
*/
export const replaceByRegex = (n, r) => h => h.replace(n, r);
``````

Notice that if a func takes exactly one arg, I don't have to curry it in order to use it in a functional pipeline.

Finally, the functional pipeline can be executed like this...

``````functionalPipeline(`
pwd
git status
git stash --include-untracked
git pull
git stash pop
`);
`````` Safin Ghoghabori • Edited

//below is currying function
const sum = a => {
return (b) => {
return a+b;
}
}

So my query is why we need to nest functions and make it currying? Why cant we simply define it as follow:

const sum = (a,b) => a+b;

In this way, we also pass a & b, whereas in first example we also pass a & b, then what is difference? What are advantages? Hi guys!

I've been looking for a nice currying example and noticed few mistakes here. Just a few notes: sum(a,b,c) function provided last is not a best example of currying because currying is "single parameter at the time" (definitely not an add(20,90) etc), so sum(a,b,c) here is, probably, a good example of partial application. imho

Here are few interesting things described on wiki:
Wiki definition of curying: In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument;
and partial application definition: In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity

p.s. this is just my imho :) Harshit Gangwar

Currying is also possible using .bind() Suprabha

I found the great article which might help for understanding between currying and partial application:
2ality.com/2011/09/currying-vs-par... Chinmay Ghule

The last part "To develop a function that takes a function and returns a curried function" was very confusing. What exactly happened there?