HIGHER-ORDER FUNCTIONS Functions as Parameters

hello community,

can vllt. someone briefly explain to me what the code here exactly fills and how the path comes about?
Link: https://www.codecademy.com/courses/introduction-to-javascript/lessons/higher-order-functions/exercises/functions-as-parameters

Great Thanks (:

We’re now describing an HOF that takes a function as one of its expected parameters. In other words,

const myHof = function (func) {

}

It’s kind of useless if there is nothing to operate the function on so we would expect another value argument to pass into the applied function…

const myHof = function (func, arg) {
    return func(arg)
}

It goes further. Connect if you wish to pursue this.

Thank you for your reply,
unfortunately I do not quite understand what you mean. Can you explain it to me maybe differently?:smiley:

You see the standalone function, addTwo()? What does that function do? It takes one parameter, supposedly a number to which it adds 2 then returns the new value.

The above function is passed into the HOF, checkConsistentOutput() as a reference only, along with a test value, val.

Inside the function we add 2 to val and assign it to one variable. We also pass val to the inputted function and assign its return value to another variable. The operation is the same in both functions, so the variables should both be equal.

When we have a function, func() and we wish to pass it by reference to another function we do not invoke the function but rather pass in only its name.

Take another look at the example above, and compare it to your exercise. Notice that only the name is used in the argument? We invoke it inside the HOF, on the given value.

There is another use case wherein arg is an iterable such as an array or object.

const addTwo = x => x + 2;

const myHof = function (func, args) {
    results = []
    for (let x of args) {
        results.push(func(x))
    }
    return results
}

console.log(myHof(addTwo, [2, 5, 8, 11, 17]))

// [4, 7, 10, 13, 19]

The function, checkConsistentOutput, is a kind of testing function. As its’ two parameters, it takes in another function and some argument or set of arguments.

In this specific case, it is used to take in the addTwo function and a provided number, and then it checks whether the addTwo function evaluates to the same thing as is described in the expression that’s stored in the checkA variable (which is value + 2).

This is an example of a higher-order function which can take in a function as one of its parameters - higher-order functions can also return a function, but that’s not what’s on display here.

Thanks for help!(:+1:

Okay, thanks for help! :+1:

1 Like