A Simple Explanation of Currying Functions(Javascript)

currying function’s usages, pros and cons

‘Currying’ has the same spelling as Curry that we love.

But ‘currying’ is derived from the name Haskell Brooks Curry who was known as a mathematician and a logician.

Currying is a technique that converting multiple arguments function into a single argument functions sequence.

Like this.

func(a, b, c) -> f(a)(b)(c)

Three arguments function is converted into three functions with single argument each.

f(a) returns value and (b) takes this value as a parameter. (c) also do the same thing. Get’s (b)‘s return value and return.

//non-curried
function plusFunc(a, b, c){
  console.log(a + b + c);
}

plusFunc(1, 2, 3);   // 6

//curried
function plusFunc(a){
    return function(b){
       return function(c){
          console.log(a + b + c);
       }
    }
}

plusFunc(1)(2)(4);  // 7

Then what are the differences between Curried and Non-curried?

non-curried : Function will be immediately executed even though parameters are not passed.
? Function definition : func(a, b, c)
? Function execution : func(a)
? Execution result : func(a, undefined, undefined)

curried : Execution will be suspended if parameters are not fully passed.
? Function definition : func(a, b, c)
? Function execution : func(a)
? Execution result : func(a) waits for b parameter.

So we can use currying as below.

function setAppell(appell){
    return function(name) {
       console.log(appell + name);   
    }
}

const setName = setAppell('Mr.');
setName('Right');  // Mr.Right
setAppell('Mr.')('Baker'); //Mr.Baker

//ES6 화살표 함수
const setAppell = appell => name => console.log(appell + name);

const setName = setAppell('Miss.');
setName('Dior');  // Miss.Dior

If we use currying function, we can also pass event and value together.

const setNumber = (num) => (event) => {
     console.log(event.target.id+':'+num);
}

<div onClick="setNumber(2)(event)" id='myNum'>
  click
</div>

// myNum:2

What is Pros.

? Pros
Reusable
– Reduced amount of code
– Readability

And Cons.

? Cons
Deeply nested functions cause memory and speed issue. So Currying

Mathematical Explanations of Currying



Most of the functions can be implemented without using currying. but you can expect a good effect if you use currying to improve productivity through reusability or readability.