DEV Community

Cover image for Function Currying - JavaScript
umerjaved178
umerjaved178

Posted on

Function Currying - JavaScript

Currying is a technique of writing function having multiple arguments, into sequence of functions with single argument. Thus it keep returning the function until all the fucntions are exhausted, arguments are remembered via Closure.

Don't know about Closure, then ignore it ;)

Let go through this simple example:


// without arguments
let dish = function () {
  return function () {
    console.log("Chicken Curry ;) ");
  };
};

dish()();
// console
// Chicken Curry ;


// with arguments
let dish = function () {
  return function (y) {
    console.log(y);
  };
};

dish()("I had crush on JS");
// console
// I had crush on JS

let multiply = function (x) {
  return function (y) {
    console.log(x*y);
  };
};

dish(2)(3);
// console
// 6
Enter fullscreen mode Exit fullscreen mode

Now a complex example

let employee = 
  name =>
    role =>
      company =>
        name + " is  a " +
        role + " in " +
        company

let output = employee('Jack')('Frontend Engineer')('Google')
console.log(output)
// console
// Jack is  a Frontend Engineer in Google

// we can also write it as 
let person = employee('Jack')
let designation = person('Frontend Engineer')
console.log(designation('Google'))
// console
// Jack is  a Frontend Engineer in Google
Enter fullscreen mode Exit fullscreen mode

Benefits

  1. It will make out function look sleek when it has multiple arguments
  2. I avoids the frequent calling of a function with the same argument, Let's see how

We have a function to calculate the volume of a cylinder
It happens that all the cylinders in your house are of height 100m.

function volume(l, w, h) {
    return l * w * h;
}

volume(200,30,100); // 600,000l
volume(32,45,100); //144000l
volume(2322,232,100); // 53870400l
Enter fullscreen mode Exit fullscreen mode

We are repeatedly using the same height in all 3 invocations.
Let's solve this using currying

function volume(h) {
    return (w) => {
        return (l) => {
            return l * w * h
        }
    }
}

const hCylinderHeight = volume(100);

hCylinderHeight(200)(30); // 600,000l
hCylinderHeight(32)(45);   //144000l
hCylinderHeight(2322)(232); // 53,870,400l
Enter fullscreen mode Exit fullscreen mode

Top comments (0)