# 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();
}

let sayBye = function() {
}

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 + " !";
}
}

``````

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;
}

``````

Eg 2 : Currying method - function accepts only 1 parameter

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

``````

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

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