Currying in JS

Currying in JS

Currying is a process in which it takes a function which have more than one parameter and converts it in function which takes only one parameter.

Currying

Let's understand using simple example

//normal function
const add = (a,b) => a + b;
console.log(add(1,2)) // 3

// curried function
const add = a => b => a + b; 
console.log(add(1)(2)); // 3

In the above example we have normal add function which takes two parameter and add them. Then we have curried function of add which takes one parameter first and then returns a function and when we call this function with another parameter which returns addition of two paramters.

Let's have another example

const curriedGreeting = mssg => user => `${mssg}, ${user}`;
const gotMssg = curriedGreeting("Good morning");
/*
Assume we are have
different code section here
*/
const greetUser = gotMssg("Jhon");
console.log(greetUser); // "Good morning, Jhon";

In the above example we have curriedGreeting function which takes message and returns another function which takes user and return a string which greets user. First we call curriedGreeting function and gives a message Good morning and stores it in gotMssg. We can observe normal function needs all parameter at once to execute, but using currying we can have function which takes single parameter at a time and can call with other parameter when we get it. So here after some code section we are calling gotMssg function with user Jhon and if we console log greetUser we get Good morning, Jhon. Currying uses clouser to remember all its arguments.

Summary

Hence we saw how currying helps to convert a normal function with n parameters to n functions