Currying at Javascript

Currying is an important technique in functional programming. It is asked as an interview question in many interviews.

Currying technique is the process of transforming a function so that it is called with a single parameter like f(a)(b)(c) each time, instead of calling it to take multiple parameters as in f(a, b, c).

Let’s take a simple look at the following example.

function sum(a,b,c) {
    return a + b + c;
};
sum(5, 10, 15);

Let’s write the sum() function with the currying technique.

const sum = (a) => {
    return (b) => {
        return (c) => {
            return a + b + c
        }
    }
}
sum(5)(10)(15);

As you can see, every time we call the function we just wrote, a new function returns.

In order to understand the Currying concept well, it is necessary to know the concept of Closure in javascript.

Advantages

  1. By calling the same function partially, we ensure that different results are returned in different parts of the project.
  2. We prevent code duplication.
  3. We avoid entering the same parameter repeatedly.

Example:

const logs = (logType) => {
  return (logDate) => {
    console.log(`${logType} : there was an issue on ${logDate}.`);
  };
};

const logDate = logs('Warning');
//1. Log Message
logDate(new Date());
//2. Log Message
logDate(new Date());

Good Luck…