cb
is an arrow function (I am assuming +>
is a typo and is meant to be =>
) which has two parameters n1
and n2
. It returns the sum of the two arguments passed in to this function.
hof
is also an arrow function. It has a single parameter func
. Nothing special about the name func
. You could name the parameter as abc
if so inclined. But func
is a better choice (as opposed to a gibberish parameter name) as it clues in anyone reading the code that when the function hof
is called, the argument passed to hof
is meant to be a function.
If the argument to a function is meant to be a number, then num
or n
or something more specific like age
, price
etc. (depending on the purpose of the function) might be good choices for naming the parameter. If the argument is meant to a string, then perhaps str
or word
or phrase
or something similar which lends to better readability may be suitable parameter names. In the example you have posted, the argument is meant to be a reference to a function, so func
is a good name choice for the parameter.
When the function call is made,
hof(cb)
we aren’t invoking the function cb
. Something like cb(23, 55)
would invoked the function cb
with 23
and 55
as the arguments. But in hof(cb)
, we aren’t passing the result of calling cb
as the argument to hof
. We aren’t invoking cb
(note the lack of parentheses and arguments). Instead, the function cb
is being passed as a callback function to hof
.
When we make a function call to hof
,
hof(cb)
then, cb
is the argument. A reference to the cb
function will be assigned to the parameter func
and within the body of the hof
function, we will use the word func
to access cb
.
Within the body of hof
, the statement
let value = func(3, 5);
will actually be equivalent to
let value = cb(3, 5);
Suppose, we add a console statement:
let cb = (n1, n2) => {return n1 + n2};
let hof = (func) => {
console.log(func);
let value = func(3, 5);
return `this function returned ${value}`;
}
console.log(hof(cb))
// Output:
// [Function: cb]
// "this function returned 8"
cb
returns the sum of two numbers. Suppose we wanted to multiply or do something else with the numbers, then we won’t need to edit hof
. We simply pass in a different callback function as the argument e.g.
let cb = (n1, n2) => {return n1 + n2};
let mul = (n1, n2) => {return n1 * n2};
let expo = (n1, n2) => {return n1 ** n2};
let hof = (func) => {
let value = func(3, 5);
return `this function returned ${value}`;
}
console.log(hof(cb)); # this function returned 8
console.log(hof(mul)); # this function returned 15
console.log(hof(expo)); # this function returned 243
We don’t have to make any changes to hof
. We just pass in a different callback function as the argument.