What is a higher order function?
JavaScript
What is a higher-order function?
A higher-order function is a function that takes one or more functions as arguments or returns a function as its result.
In JavaScript, functions are first-class objects, which means they can be passed around like any other value. This allows for powerful and flexible programming patterns, such as callbacks, closures, and function composition.
Higher-order functions are a key feature of functional programming, which emphasizes the use of pure functions, immutability, and composition over inheritance.
Examples
javascript
function higherOrderFunction(fn) {fn();}
Real world examples
javascript
// Example 1: map() is a higher-order function because// it takes a function as an argumentnumbers.map(num => num * 2)// ^^^^^^^^^^^^ This is the function being passed as an argument// Example 2: filter() is a higher-order function because// it takes a function as an argumentconst isEven = num => num % 2 === 0;numbers.filter(isEven)// ^^^^^^ This function is passed as an argument// Example 3: reduce() is a higher-order function because// it takes a function as an argumentnumbers.reduce((total, current) => total + current, 0)// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This function is passed as an argument// Example 4: multiplier() is a higher-order function because// it returns a functionfunction multiplier(factor) {return number => number * factor; // <- Returns a function}// Example 5: compose() is a higher-order function because it:// 1. Takes two functions as arguments (f and g)// 2. Returns a new functionconst compose = (f, g) => x => f(g(x));// Example 6: debounce() is a higher-order function because it:// 1. Takes a function as an argument (func)// 2. Returns a new functionfunction debounce(func, delay) {return function(...args) { ... } // <- Returns a function}