Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

JavaScript

Access all courses and lessons, track your progress, gain confidence and expertise.

Instructor: Inside this file we see three different functions that perform some sort of computation to a number. If we want to run these functions together, we could chain them together like so. In this instance we want to run them, in order according to their line number, to compute a number from the start val constant at the top of the page.

When chaining functions, the innermost function will be executed first. This then continues towards the outermost function, which, in our case, is going to be add 10. Now if I execute this in my terminal, we see that the function is working correctly, as it's printing out 42.

Let's quickly add another function that would just divide this number in half. If I wrap these nested functions in this half num function I just created, then the prompt should print 21 when I run this command. It does.

This is great, but there has to be a more elegant way of performing this, right? Cue the compose function. The compose function takes in an array of functions, as well as a starting point. From there it uses JavaScript's reduceRight method to map through the array of functions and apply them to the result of the previous function being returned.

We must pass in an initial value into reduceRight to specify our start value. Since compose is a curried function, we're going to be passing our values in separate parenthesis blocks. As we just saw, the left parens group is going to hold our array of functions, while the second is where we're going to place our initial value, which, in this case, is the start val const.

As its name suggests, reduceRight is going to apply our functions from right to left. Therefore, we're going to need to pass our functions in, like so. First we have half num, then add 10, then doubled, and then finally squared, which is going to be the first function that will act on our start value. Now that our function is ready to go, we can execute this script and we'll again see 21 being printed out.