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.