Build Complex Functions with Function Composition in JavaScript

Composing functions is fundamental to functional programming. Luckily, you probably have already done some functional composition in high school or college math class. Understanding the compose() function will enable you to easily build complex functionality in your applications and programs.

You must be a Member to view code

Instructor: 00:00 You might recall having something where you had a function named F that took a value and returned an output from that function. In this case, we'll just add 1 to our value.

00:11 Then, we might have a second function that also takes a value. In this case, we'll double it. Lastly, we'll add a value. In this case, X will equal 3.

00:21 Composition is then simply nesting the result of one function as the input to another function. You might recall seeing something that looked like this. If we log out the result, we should see that. X of 3 is given to the function G, which multiplies it by 2 and gives us 6. 6 is then given to F, which means our result should equal 7.

00:48 That's the gist of functional composition. It's the nesting of one function inside another, passing the result from one into the other, until we get our final result. Let's do this with slightly more useful functions.

01:01 First, let's have a scream function that uppercases any string. Next, an exclaim function that adds an exclamation point to any string. Finally, a repeat function that will simply repeat our string.

01:17 Now, we can create a string, and we could do composition, just like before. First, we'll want to scream it, and then we will want to exclaim it, which means we have to wrap the result of scream. We might want to repeat it, which means we have to wrap both of those.

01:38 If we log this out, we should see "EGGHEAD.IO IS AWESOME" in all caps, repeated, and exclaimed. This can be really unwieldy, nesting functions like this. There has to be a better way. The way we can do that is through creating a compose function.

01:55 Compose will take any number of functions and return a function that awaits a value, and then reduce those functions down, just like our composition before.

02:08 To make sense of this, our functions are turned into an array using the rest operator, and we reduce right, starting from our final function moving leftwards, and pass the result of the previous functions into the current function. We start with the value X.

02:26 Thus, we can make a new function using our compose function. Now, using reduce right means that the furthest right argument is our first one. First, we want to scream, then we want to exclaim, and then we want to repeat. This produces a new function which we can use on our string.

02:48 We save this and we log it out on the terminal, we should get the same result.