Become a member
to unlock all features

Level Up!

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


    Modify Functions with Higher Order Functions in JavaScript


    This lesson teaches the concept of higher order functions (HOF) in JavaScript, a necessary building block of functional programming in any language.

    A higher order function does at least one of the following things, often both:

    1. Accepts a function as an argument
    2. Returns a new function

    To demonstrate this, we will build a higher order function, withCount(), that modifies any function passed to it so that it logs out how many times it has been called.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: A higher order function is any function that does at least one of the following two things, and oftentimes does both. First, it accepts a function as an argument. Second, it might return a new function.

    To demonstrate this, we're going to create a width, count higher-order function. With count, we'll take a function as an argument. What it will do is return a console log of how many times we've called our newly return function from within it.

    To do this, we'll store a count variable. We'll return a new function that uses the rest operator to gather up the arguments passed to it. Inside the body of our return function, we'll log out the count while also incrementing it. We'll return the results of the function that's been called with the spread arguments.

    Now that we have our width, count higher-order function, let's create a simple add function to use and pass into it. It will receive X and Y as arguments and return their summation. We can now create a counted add function by using our width, count function and passing add to it.

    Now, let's log out several uses of counted add. I'll modify some of the arguments. If we save this and print it out in the terminal, we should see a call count with each one.