Function Composition

Introduction to function composition in JavaScript.

Background

In functional programming, you tend to create specialized functions that complete certain tasks. In these cases, programmers rely on abstractions and expect the function to work. However, these practices can lead to chaining multiple functions, resulting in calling many functions, one after the other. To beautify code and make your life easier, use function composition.

Introduction to function composition

Function composition is an approach where the result of one function is passed to the next function, and then to another, until the final function is executed. They can be composed of any number of functions.

Before we can jump into function composition, let’s learn about curry functions.

Curry functions

The concept of curry functions involves functions that take one argument and return a new function, which also takes one argument.

Take a look at the following example.

Press + to interact
var add = function (a){
return function(b){
return a + b;
}
}
// console.log(add(a,b)); <- incorrect call
// calling one function at a time
var func_add_2 = add(1); // return a function which adds 1 to the argument
var final_output = func_add_2(5);
console.log(final_output);
// more direct approach
final_output = add(1)(5);
console.log(final_output);

In the code above, function add takes only one argument and returns another function, which also takes only one argument, and adds the argument of add function to it. We invoke add function on line 8, take the return function to invoke it in the very next line, and then assign the ...