What Is Higher Order Function (HOF)
What Is Higher Order Function (HOF)
Higher-order functions
The functions that use only primitives (predefined data types) or objects as arguments, and only return
primitives or objects are named first-order functions.
However, functions are treated as first-class citizens in JavaScript which means that functions can be
return 'Hello!'
};
hello();
function useFunction(func) {
return func();
function returnFunction() {
exFunc();
Higher-order functions are, in fact, functions that accept another function as an argument or return another
function. In the above examples, useFunction() is a higher-order function because it accepts a function as an
argument. Also, returnFunction() is a higher-order function because it returns another function.
Examples of HOF
EXAMPLE 1
function calculatorFunction(operation, initialValue,
numbers) {
return total;
return n1 + n2;
return n1 * n2;
sum() is the function that describes the addition operation. calculatorFunction(sum, 0, [1, 3, 4]) is using sum()
function to perform the sum of numbers.
Similarly, multiply() describes the multiplication operation. calculatorFunction(multiply, 1, [1, 3, 4]) is using
multiply() function to perform the product of numbers.
EXAMPLE 2
function createMultiplier(factor) {
return function(number) {
};
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
In the above example, the createMultiplier function is a higher-order function because it returns a new
function. The createMultiplier function takes a factor as an argument and returns an inner function. The inner
function takes a number as an argument and multiplies it by the factor provided to the createMultiplier
function. We can then use the createMultiplier function to create specific multiplier functions, such as double
and triple. The double function multiplies a number by 2, and the triple function multiplies a number by 3. We
can call these functions with a number as an argument to perform the respective multiplication.
In the above examples of HOF we had seen the usage of callback functions.
Let’s take an example where we want to double the value of all the elements of the array -
function doubleNumber(number) {
return number * 2;
// output
// Original Numbers: [ 1, 2, 3, 4, 5 ]
// Doubled Numbers: [ 2, 4, 6, 8, 10 ]
Function Composition
Function composition is the process of combining two or more functions to produce a new function.
Higher-order functions enable composing functions by taking one function's output and passing it as an
input to another function.
In the below example, we are composition two simple functions into one by using HOF -
console.log(result); // Output: 36
Question 1: Implement a findIndex function that returns the index of the first element in an array that satisfies a
given condition.
if (callback(arr[i])) {
return i;
// Example usage
callback(arr[i], i, arr);
// Example usage