What are Higher-Order Functions in JavaScript (HOF)
Higher-Order Function (HOF) is a function that takes another function as an argument or returns a function as a result.
Simply Put:
If a function can work with another function (accept, return or both), it's a higher-order function.
Examples of Higher-Order Functions
Takes Another Function as Argument
function greet(name) {
return `Hello, ${name}`;
}
function processUserInput(callback) {
const name = "Alice";
return callback(name);
}
console.log(processUserInput(greet)); // "Hello, Alice"
Here processUserInput is a higher-order function since it takes another function greet as an argument.
Returns a Function
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10
In this example multiplier returns another function — so it's also a higher-order function.
Where are Higher-Order Functions Used?
JavaScript actively uses HOF in built-in array methods: map, filter, reduce, forEach.
Example with map
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
The map method is a higher-order function because it accepts another function (num => num * 2) as an argument.
Why are HOF Needed?
- Increase code flexibility and reusability
- Improve abstraction — you can write more general behavior not dependent on specific actions
- Allow implementing closures, decorators, partial application and other powerful concepts
Summary
Higher-order functions are functions that:
- Accept other functions as arguments
- Return functions as results
- Used extensively in functional programming and JavaScript