A Higher-Order Function is a function that either:
- Takes one or more functions as arguments
- Returns a function as its result
- Or both.
💡 Think of it as "functions that operate on other functions."
function greet(name) {
return `Hello, ${name}`;
}
function processUserInput(callback) {
const name = 'Alice';
console.log(callback(name));
}
processUserInput(greet);
// Output: Hello, AliceHere:
processUserInputis a HOF because it acceptsgreet(a function) as an argument.
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10Here:
multiplieris a HOF because it returns another function.
- They make code more reusable and declarative.
- Enable abstraction of behavior (you pass what to do instead of how to do it).
- Essential for functional programming patterns.
Many JS array methods are higher-order functions:
const numbers = [1, 2, 3];
numbers.map((num) => num * 2); // HOF → map takes a function
numbers.filter((num) => num > 1); // HOF → filter takes a function
numbers.reduce((a, b) => a + b); // HOF → reduce takes a functionFunctional Programming is a programming paradigm where:
- Computation is treated as the evaluation of pure functions.
- State and data are immutable.
- Functions are first-class citizens (can be stored in variables, passed, or returned).
- Avoids side effects.
- Pure Functions → Same input → Same output, no side effects.
- Immutability → Do not modify existing data; instead, create new data.
- Function Composition → Build complex functions from simpler ones.
- First-Class Functions → Treat functions like any other variable.
- Higher-Order Functions → Use functions to operate on functions.
// Pure, immutable, declarative
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // [2, 4, 6, 8]Instead of looping and mutating arrays, FP uses HOFs for cleaner, declarative code.
A Higher-Order Function is a function that takes one or more functions as arguments, returns a function, or both. They're a key part of functional programming, which treats functions as first-class citizens, avoids side effects, and promotes immutability. Examples include map, filter, reduce. HOFs help abstract behavior, make code reusable, and allow composition of small pure functions into more complex ones.