DEV Community

Vanmeeganathan P K
Vanmeeganathan P K

Posted on

Currying Functions

Currying refers to transforming functions with multiple arguments into a function accepting a single argument at a time.

It is usually achieved by having the function return another function which in turn takes the next argument as its only parameter.

This is often difficult for the beginners to understand. Let us begin by understanding higher order functions.

Higher Order Functions

Unlike many other languages, javascript allows functions to take another function as a parameter. It also allows a function to be returned as a result.

A function which takes another function as a parameter or that which returns another function is a higher order function.

Eg 1: Function taking another function as parameter

let sayHi = function(sayBye) {
    sayBye();
    alert("Hi !!");
}

let sayBye = function() {
    alert("Bye !!");
}

sayHi(sayBye);

Can you predict the order in which the alerts will get prompted ?

In the above example. sayHi() is a higher order function.

Eg 2: Function returning another function as parameter

let sayBye = function(name) {
    return function() {
    return "Bye "+ name + " !";
  }
}

alert(sayBye("Raj"));

alert(sayBye("Raj")());

Can you predict the output of the above two alert prompts ?

Here, sayBye() is a higher order function since it returns another function.

Once you are good with higher order functions, you are ready for understanding currying. Let us try a simple example for adding two numbers.

Eg 1 : Normal method - function accepts more than 1 parameter

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

let result = add(10,12);
alert(result);

Eg 2 : Currying method - function accepts only 1 parameter


let add = function (a) {
  return function (b) {
    return a + b;
  };
};

let result = add(10)(12);
alert(result);

add(10) returns a function.

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

for the above function, when 12 is passed as parameter, we get 22 as the result.

In the above example, both these calls are made in a single statement.

let result = add(10)(12);

Let us try currying for a function which finds the power of a number.

  • Without Currying
let power = function (power, number) {
  let product = 1;
  for (let i = 1; i <= power; i++) {
    product *= number;
  }
  return product;
};

alert(power(3, 2));
  • With Currying
let power = function (power) {
  return function (number) {
    let product = 1;
    for (let i = 1; i <= power; i++) {
      product *= number;
    }
    return product;
  };
};

let cube = power(3);

alert(cube(2));
alert(cube(3));

Hope this helped you understand currying! Continue the fun with currying!

Top comments (0)