DEV Community

Discussion on: Introduction to Currying in JavaScript

 
vonheikemen profile image
Heiker • Edited

What I'm about to say is just my opinion. Not going to claim this is the absolute truth.

"The point" of currying is to enable better function composition.

Let me present a very popular function called pipe.

function pipe(...chain_of_functions) {
  return (init) => {
    let state = init;

    for(let func of chain_of_functions) {
      state = func(state);
    }

    return state;
  }
}
Enter fullscreen mode Exit fullscreen mode

This allows us to convert this.

last_fun(second_fun(first_fun('something')));
Enter fullscreen mode Exit fullscreen mode

Into this.

const final_fun = pipe(first_fun, second_fun, last_fun);

final_fun('something');
Enter fullscreen mode Exit fullscreen mode

This seems cool... until you realise each function just takes one argument. We got ourselves a real problem here. We want to create functions with pipe (we can't change its implementation) and we also want to use functions with multiple arguments.

One answer to this problem is currying. If literally all your functions take one argument you'll never have to face this issue while using pipe.

Let's say that second_fun needs two arguments. Fine. Curry it.

const second_fun = (one) => (two) => {
  // do stuff
}
Enter fullscreen mode Exit fullscreen mode

Now you're free to do this.

const final_fun = pipe(first_fun, second_fun('WOW'), last_fun);
Enter fullscreen mode Exit fullscreen mode

It'll work like a charm.

But is this better? More readable? I can't answer that for you. It's a matter of style. Do what makes you happy.