Currying in Javascript

Currying is a concept where a function with multiple arguments is divided into multiple functions having 1 or 2 arguments.

Syntax of Currying Function

function multipleargs(arg1, arg2, arg3, arg4)

curriedfunction(arg1)(arg2)(arg3)(arg4)

There is an inner function present inside another function & the inner function is returned and it goes on until all the arguments are traversed successfully.

How does currying help in javascript?

1. Currying helps in creating higher-order functions.

2. Currying divides the main function into several components which helps in debugging in an easier manner.

3. Currying can help in building more readable & reusable code.

Here’s an example of currying in javascript:

Code:

//Normal Method

function multiplication(a1,a2,a3){
    return a1*a2*a3;
}

//Method Created using Currying
function multiplicationbycurry(a1){
    return function temp(a2){
        return function temp2(a3){
            return a1*a2*a3;
        }
    }
}
let res=multiplicationbycurry(2)(3)(5);
console.log(res);

Output:

30

In the above code, we can see that there is a single function named as multiplication taking three parameters inside it & multiplying them in one line.

Now there is a currying function named as multiplicationbycurry taking only one parameter & it contains an inner function named as temp taking one parameter and then this function also has an inner function named as temp2 taking one parameter as well.

I hope you understood how basic currying works and that is all for this blog. In future blogs, we might cover some Advanced currying techniques as well. Feel free to ask your doubts below or type your thoughts in the comment box.