Higher Order Function (HOF) is a function that can take a function as an argument or a function that return another function.
Array.map is HOF, in below case, map receive an arrow function as an argument.
['cat', 'dog', 'bird'].map(animal => `Hi, ${animal}`)
Let's have a look another example
This function take num1
as an argument, then return a function function (num2) {return num1 * num2}
. So it's HOF.
const multiplyBy = function (num1){
return function (num2) {
return num1 * num2
}
}
const multiplyByTwo = multiplyBy(2)
const multiplyByFive = multiplyBy(5)
multiplyByTwo(5) // 10
multiplyByFive(5) // 25
Let's convert above method.
const multiplyBy = num1 => num2 => num1 * num2
multiplyBy(2)(5) // 10
Top comments (7)
A simpler way to write 'multiplyBy' would just be:
Thank you for correcting, I forgot to add
return
or remove{}
.According to Wikipedia, there is a description about
HOF
.In mathematics and computer science, a higher-order function is a function that does at least one of the following: takes one or more functions as arguments, returns a function as its result.
Your examples are about
closure
.Below one is able to be one of examples of
HOF
.In developer.mozilla.org/en-US/docs/W..., there is this example.
The OP's example is a perfectly good example of a HOF, and is all but identical to the example from MDN - which is also a good example of a HOF. The fact that a closure is involved in the creation of the HOF is irrelevant.
Your own example also makes use of a closure, and actually does both of the things that the definition of a HOF requires at least one of: it takes a function as input, and also returns a function. Both things are not necessary for it to be a higher order function.
Yes, I used a closure to implement a HOF. I just wanted to show that HOF takes a funtion as input.
That isn't correct, even by the definition you provided:
It only needs take take a function as input, or return a function as output to be a HOF. It can do both too, but that's not necessary.
Oh, return a function as output. I've written wrong information. Thank you for correcting me :)