Higher-Order Function
Higher-Order Function
A function that takes functions as arguments or returns a function. map, filter, and reduce are typical examples.
Higher-Order Function
A function that takes functions as arguments or returns a function. map, filter, and reduce are typical examples.
A higher-order function is a function that takes a function as an argument or returns a function. This concept is a core principle of functional programming and is implemented naturally in languages that treat functions as first-class citizens. Most modern programming languages, including JavaScript, Python, and Haskell, support higher-order functions.
The most representative higher-order functions are map, filter, and reduce. map applies a function to each element of an array to create a new array, filter extracts only the elements that satisfy a condition, and reduce collapses an array into a single value. They replace for loops and make code more declarative and easier to read.
The key advantages of higher-order functions are abstraction and reusability. Abstracting repeated patterns into functions reduces code duplication, and functions can be combined to build complex logic. They also reduce side effects, making testing and debugging easier.
In practice, higher-order functions are used in many places, such as event handler registration, callback patterns, middleware implementation, and the decorator pattern. React's higher-order components (HOC), Redux's middleware, and Express's router chain are all applications of the principles of higher-order functions. It is a concept that must be understood in modern frontend development.
// 1. 기본 고차 함수: 함수를 인자로 받는 경우
const numbers = [1, 2, 3, 4, 5];
// map: 각 요소를 변환
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: 조건에 맞는 요소만 추출
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce: 배열을 하나의 값으로 축약
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// 2. 함수를 반환하는 고차 함수
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
// 3. 실용적인 예제: 커링(Currying)
const curry = (fn) => {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return (...nextArgs) => curried(...args, ...nextArgs);
};
};
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6
console.log(curriedAdd(1)(2, 3)); // 6
// 4. 함수 합성(Composition)
const compose = (...fns) => (x) =>
fns.reduceRight((acc, fn) => fn(acc), x);
const addOne = x => x + 1;
const square = x => x * x;
const toString = x => `Result: ${x}`;
const compute = compose(toString, square, addOne);
console.log(compute(4)); // "Result: 25" (4+1=5, 5^2=25)
"I think we can handle this data transformation logic by chaining map and filter. It's more readable than a for loop, and it's easier to check the intermediate results. For the performance-critical parts, let's also consider handling them in one pass with reduce."
"A higher-order function is a function that takes a function as an argument or returns one. Typical examples are Array's map, filter, and reduce. Using them, you can implement functional programming patterns such as function composition and currying. React's HOC is also an application of higher-order functions."
"What if we use reduce instead of modifying an external variable in forEach here? You can produce the result without side effects, so debugging is easier, and it's also good for writing tests at the function level."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
map is for transformation, and filter is for extraction. If map returns undefined, the array length is preserved, and if you transform elements in filter, you get unintended results. Choose the method that fits the purpose.
Iterating multiple times, as in map().filter().map(), causes performance problems with large datasets. Process in one pass with reduce, or chain only when truly necessary.
If you pass a regular function as a callback, this changes. Use an arrow function, or bind explicitly with bind(). Special care is needed when passing a class method as a callback.
Make the callbacks you pass to higher-order functions small and pure. They are reusable, easy to test, and you can build complex logic through function composition.