Table of Contents

Java Script HOF (High Order Function)

(HOF) is a function that takes one or more functions as arguments and/or returns a function as its result. HOFs are a powerful feature in JavaScript and enable functional programming patterns.

A function qualifies as HOF if it does any of the following:

Taking a function as an argument

function runFunction(fn) {
  return fn();
}
 
function sayHello() {
  return 'Hello, world!';
}
 
const result = runFunction(sayHello);
console.log(result); // Outputs: Hello, world!

Returning a function

function multiplier(factor) {
  return function(x) {
    return x * factor;
  };
}
 
const timesTwo = multiplier(2);
console.log(timesTwo(5)); // Outputs: 10

Both Taking a Function as an Argument and Returning a Function

function compose(f, g) {
  return function(x) {
    return f(g(x));
  };
}
 
const addOne = x => x + 1;
const double = x => x * 2;
 
const addOneThenDouble = compose(double, addOne);
 
console.log(addOneThenDouble(2)); // Outputs: 6
Higher-order functions enable more abstract and concise code, promote reusability, and facilitate functional programming techniques like currying, partial application, and composition.
Functions like map, filter, and reduce are examples of built-in higher-order functions in JavaScript.

HOF vs Callback

A callback is a function that is passed as an argument to another function and is expected to be executed at some point in the future, either asynchronously or after some computation.
Essentially, a callback is a specific instance of a function argument that a HOF might take.
Example:

function fetchData(url, callback) {
  // Simulating an async operation
  setTimeout(() => {
    const data = "Some data from " + url;
    callback(data);
  }, 1000);
}

fetchData('http://example.com', (result) => {
  console.log(result);
});

In this example, the anonymous function passed as the second argument to fetchData is a callback. It gets executed after a timeout.

HOF refers to the concept of functions operating on other functions by taking them as arguments, returning them, or both.

Callback refers to a specific function that is meant to be executed at a later time or after some computation, and is often passed to a HOF.

In other words, a callback is a type of argument that a higher-order function might accept. It is a pattern used for deferred or asynchronous operations. So, while all callbacks used in this way are an example of higher-order functions, not all higher-order functions are using callbacks for deferred or asynchronous execution.