Junior
What is a higher-order function?
sobes.tech AI
Answer from AI
A higher-order function is a function that:
- Accepts one or more functions as arguments.
- Returns another function as a result.
Such functions allow abstraction from specific actions, increasing flexibility and reusability of code.
Examples in JavaScript: map, filter, reduce, setTimeout.
// Example of a higher-order function: Function as an argument
function applyOperation(x, y, operation) {
return operation(x, y);
}
function add(a, b) {
return a + b;
}
const result = applyOperation(5, 3, add); // Passing function `add` as an argument
console.log(result); // 8
// Example of a higher-order function: Returning a function
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const multiplyByTwo = multiplyBy(2); // Returning a new function
const value = multiplyByTwo(10); // Using the returned function
console.log(value); // 20
Advantages:
- Improves readability and modularity of code.
- Facilitates creation of abstractions.
- Promotes functional programming style.