(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:
function runFunction(fn) { return fn(); } function sayHello() { return 'Hello, world!'; } const result = runFunction(sayHello); console.log(result); // Outputs: Hello, world!
function multiplier(factor) { return function(x) { return x * factor; }; } const timesTwo = multiplier(2); console.log(timesTwo(5)); // Outputs: 10
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
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.