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:
- Takes a function or more as an argument: If a function accepts another function as a parameter, it's a HOF, even if it doesn't return a function itself.
- Returns a function: If a function returns another function, it's also considered a HOF, even if it doesn't take a function as an argument.
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
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.