Become a member
to unlock all features

Level Up!

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


    Compose multiple functions for new behavior in JavaScript

    Thomas GrecoThomas Greco

    In this lesson you will create a utility function that allows you to quickly compose behavior of multiple functions to create new behavior. By the end, you will have successfully created a tremendously popular helper function that is used in JavaScript libraries ranging from Redux to Ramda.



    Become a Member to view code

    You must be a Member to view code

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

    Become a Member
    and unlock code for this lesson




    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.