4 min read
•Question 15 of 50mediumWhat are Higher-Order Functions?
Understanding functions that operate on other functions.
What You'll Learn
- What higher-order functions are
- Functions as arguments
- Functions returning functions
Definition
A higher-order function is a function that:
- Takes one or more functions as arguments, OR
- Returns a function
Examples
code.jsJavaScript
// Function as argument
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
// Custom higher-order function
function withLogging(fn) {
return function(...args) {
console.log('Calling with:', args);
const result = fn(...args);
console.log('Result:', result);
return result;
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// Calling with: [2, 3]
// Result: 5Common Higher-Order Functions
code.jsJavaScript
// Array methods
[1,2,3].map(fn)
[1,2,3].filter(fn)
[1,2,3].reduce(fn, init)
[1,2,3].forEach(fn)
[1,2,3].find(fn)
[1,2,3].some(fn)
[1,2,3].every(fn)
// setTimeout/setInterval
setTimeout(fn, delay)
// Event listeners
element.addEventListener('click', fn)