Reputation: 5
See two functions below. They lead to the same output [4,6], but are different in set up. Is it correct that only the first function makes use of a callback function? Is the first function preferred(more elegant?) over the other one? And is it correct that 'map' is the higher-order function in the second example as it makes use of the callback function that is within its brackets? Thanks!
function processArray(arr,callback){
return arr.map(callback)
}
processArray([2,3], function(number){return number*2})
AND
function processArray(arr){
return arr.map(function(element){
return otherFunction(element)})
}
function otherFunction(number){
return number*2}
processArray([2,3])
Upvotes: 0
Views: 90
Reputation: 62636
Is it correct that only the first function makes use of a callback function?
No. arr.map
takes a callback. You just don't see its definition here.
Is the first function preferred(more elegant?) over the other one?
Yes, but (probably) not for the reason you think. The anonymous function wrapping otherFunction
is pointless. You can also write
function processArray(arr){
return arr.map(otherFunction)
}
function otherFunction(number){
return number*2
}
processArray([2,3])
And is it correct that 'map' is the higher-order function in the second example as it makes use of the callback function that is within its brackets?
In the first example, both processArray
and map
are higher-order functions. In the second, yes, only map
is higher-order.
It's easy to inspect a function to see if it is a higher-order function: is one (or more) of its parameters invoked?
Upvotes: 1