higherOrderFunc: Learn Javascript-Iterators-Higher order functions-functions as parameters lesson 3/4

I understand that we are specifying param in the function higherOrderFunc and passing anotherFunc as the argument when we call higherOrderFunc(anotherFunc), I don’t get the purpose of calling param() in the body of higherOrderFunc, and no explanation is provided in the lesson text other than ‘Inside the body, param gets invoked using parentheses’. That explains what we’re doing but not why it is necessary. So…why is it necessary? Isn’t anotherFunc invoked as the callback function when passed as the argument to param? If I comment out param(), and console.log(higherOrderFunc(anotherFunc), higherOrderFunc still takes the argument anotherFunc and the code still executes. I’m trying to understand each line of what is happening in the example, can anyone explain? disclaimer: my experience with JS is the Codecademy course to this point =)

A Javascript function is actually an object that contains the instructions for what to do when the function is called. Supplying a callback function as an argument to a function passes the function object itself and not the result of calling that function. So the callback will not be called unless we explicitly call it. Passing param into the function like this higherOrderFunc(param) only makes param available to use inside of higherOrderFunc. How it gets used is up to us. We can access the name of the callback function with param.name, or we can call the function param().

It is a confusing example because passing anotherFunc into higherOrderFunc and then calling param() inside higherOrderFunc actually does nothing. It returns the string “I just invoked…”, but higherOrderFunc just ignores it. It doesn’t save the string or do anything with it.

However, if we console.log() the string that results from calling param() we will see “I’m being invoked by the higher-order function!” printed to the console because we actually told JS to do something with the string returned by anotherFunc.

Definitely not an easy topic

1 Like

Thanks for the explanation! So it does…nothing. That’s the conclusion I think I came to, but was convinced I was wrong and param() must serve an important syntactical purpose or it wouldn’t be given in the example. I think there is a side lesson to learn here about accepting Codecademy’s examples as authoritative. Again, first day on the topic!

1 Like