Mavis

Posted on

# Higher Order Function in JavaScript

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

Jon Randy 🎖️

A simpler way to write 'multiplyBy' would just be:

const multiplyBy = num1 => num2 => num1 * num2

Mavis

Thank you for correcting, I forgot to add return or remove {}.

SeongKuk Han • Edited

According to Wikipedia, there is a description about HOF.

Below one is able to be one of examples of HOF.

const greeting = (funcA) => {
return (name) => {
funcA();
console.log(`My name is \${name}.`);
}
}

const welcome = () => console.log('Welcome!');

greeting(welcome)('Mavis');

const hello = greeting(welcome);
hello('Mavis');

In developer.mozilla.org/en-US/docs/W..., there is this example.

return function (y) {
return x + y;
};
}

Jon Randy 🎖️ • Edited

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.

SeongKuk Han

Yes, I used a closure to implement a HOF. I just wanted to show that HOF takes a funtion as input.

Jon Randy 🎖️ • Edited

That isn't correct, even by the definition you provided:

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.

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.