Easy explanation of currying【JS】

Tomoharu Tsutsumi
2 min readJan 19, 2020

I’ve learned currying this week, so I’ll take a note.

What is currying?

In short, it is “deleting duplicated codes by using a function that return a function ”. Knowing examples is easier than getting examination, so I’ll show an example.

//currying
const add = x => y => x + y
add(3)(5)
//=> 8

This is currying. It is different from a normal arrow function.

//normal arrow function
const add = (x, y) => x + y
add(3, 5)
//=> 8

In case of currying, firstly, when add(3) is executed, ‘ y => x + y ’ is returned. It returns the function, and when ‘(5)’ is added, ‘ y ’ becomes ‘ 5 ’, so 8 is returned. You can see this flow with “console.log”.

What is a merit?

If you’ll use this technique, what good thing will happen? It is “deleting duplicated programmes”. The difference between normal arrow function and currying is below.

//normal arrow function
const add = (x, y) => x + y
add(1, 2) //=> 3
add(1, 4) //=> 5
add(1, 7) //=> 8
//add(1) is duplicated, it is not good!//currying
const add = x => y => x + y
const add1 = add(1)
const add1(2) //=> 3
const add1(4) //=> 5
const add1(7) //=> 8
//duplicated programmes are deleted, so it is good!

This is the merit of using currying.

Wrap up

I think currying is not so difficult, and useful. I recommend this.

If you think this article good, please follow me!

I update an article once a week!

https://twitter.com/tomoharutsutsum

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet