JavaScript Basic
What is a Higher-Order Function?
Definition
A Higher-Order Function is a function that satisfies at least one of these conditions:
- Accepts a function as an argument
- Returns a function
This is a core concept in functional programming. JavaScript supports higher-order functions natively because functions are first-class citizens.
Examples
1. Accepting a Function as an Argument
// map, filter, and reduce are all higher-order functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
// Custom higher-order function
function applyToAll(arr, fn) {
return arr.map(fn);
}
applyToAll([1, 2, 3], x => x * x); // [1, 4, 9]
2. Returning a Function
// Function factory
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
double(5); // 10
triple(5); // 15
3. Currying
const add = a => b => a + b;
const add5 = add(5);
add5(3); // 8
add5(10); // 15
Benefits
- Reusability: Separates generic logic from specific operations
- Conciseness: Reduces repetitive code
- Composability: Functions can be freely combined
- Testability: Pure functions have no side effects
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
