DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on • Edited on

Function curring

This article makes more sense if you know about javascript closures. If you want to know about closures please go through this (javascript closures) article.

What is a curried function?

A curried function is a function that accepts multiple arguments one by one. For example, a curried function of three arguments takes the first argument and returns a function that takes the second argument and returns a function that takes the final argument and returns the final result.

Example:
Let's implement a function that takes three arguments and returns the sum at the final.

function sum(a){
  return function(b){
    return function(c){
      return a+b+c;
    }
  }
}
console.log(sum(1)(2)(3));

If you are fan of es6 you can write this in single line

const sum = a => b => c => a + b + c;
console.log(sum(1)(2)(3));

Here, the sum(1) is being called that assigns a as 1 and returns a function which accepts b. Then the returned function will be called with 2 as argument and that will be assigned to b and another is function will be returned.Again, the returned function will be called with 3 as it's argument and finally our end result which is the sum of a,b,c will be returned.

Why currying?

Function currying is very useful in the case of function compositions. Especially in algebra we have function definitions as follow.

f: a -> b
g: b -> c
h: a -> c === g(f(x))

let's take a simple math example

f(x) = x + 1
g(x) = x * 2 
Now h(x) = g(f(x)) = g(x+1) = 2 * (x+1) = 2x+2

In javascript we can build this composition as follow.

const f = x => x + 1; // f(x)
const g = x => x * 2; // g(x)
const compose = (f,g) => x => g(f(x)) // a function that returns a composition of f and g
const h = compose(f,g); // composite function h(x)

I hope this adds something to your knowledge and useful ✌.

Before software can be reusable, it first has to be usable.
– Ralph Johnson

I am always open to suggestions and accept mistakes. So please leave a comment whatever you feel 🤗

Top comments (1)

Collapse
 
vishnubaliga profile image
Vishnu Baliga

Well written! 😊 Will be useful for all the js newbies out there..