Problem Statement
What is a higher-order function?
Explanation
A higher-order function is a function that either takes one or more functions as arguments, or returns a function as its result.
Array methods like map, filter, and reduce are higher-order functions because they take callback functions as arguments.
Higher-order functions enable functional programming patterns and code reuse.
They are fundamental to JavaScript and used extensively in modern frameworks.
Understanding higher-order functions shows mastery of JavaScript functions and callbacks.
Examples: map, filter, reduce, forEach, setTimeout, and functions that return other functions.
Code Solution
SolutionRead Only
// Takes function as argument
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, console.log);
// Output: 0, 1, 2
// Returns a function
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
// Array methods are higher-order functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Practical example - once function
function once(fn) {
let called = false;
return function(...args) {
if (!called) {
called = true;
return fn(...args);
}
};
}
const initialize = once(() => {
console.log('Initialized!');
});
initialize(); // 'Initialized!'
initialize(); // (nothing happens)
initialize(); // (nothing happens)