Introduction
Function composition is a mechanism for combining many simple functions to create a more complicated one. Each function's output is passed on to the next. In mathematics, we frequently use the notation f(g(x)). The result of g(x) is the value passed into f. We may achieve the composition in programming by writing something similar.
Some functions are present that help achieve function composition at ease, like Compose and Pipe functions.
Let’s learn about function composition with the help of simple and helpful code examples.
What is Function Composition?
Function composition is a method where the output of one function is passed on to the next function, which is passed on to the next, and so on until the final function is executed for the final result.
Function compositions can be made of any number of functions.
Let’s see how composition works traditionally.
// Tradition approach
const double = x => x * 2
const cube = x => x * x * x
//Method 1
let result1 = double(2);
let result2 = cube(result1);
console.log(result2);
//Method 2
let final_result = cube(double((5)));
console.log(final_result);
Output:
In the code above, we can see that we need to call the double function followed by the cube function to cube a term that has been doubled. We can do this by either assigning the values individually in variables and calling functions onto them like Method 1, or we could use a more direct approach like Method 2.
Both the methods will become complex if the number of functions increases too much. We can use an alternate approach of using Compose and Pipe functions in this case.
Let’s learn how to use compose and pipe functions to achieve function composition.