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
1function higherOrderFunction(fn) {2 fn();3}
Real world examples
JAVASCRIPT
1// Example 1: map() is a higher-order function because2// it takes a function as an argument3numbers.map(num => num * 2)4// ^^^^^^^^^^^^ This is the function being passed as an argument56// Example 2: filter() is a higher-order function because7// it takes a function as an argument8const isEven = num => num % 2 === 0;9numbers.filter(isEven)10// ^^^^^^ This function is passed as an argument1112// Example 3: reduce() is a higher-order function because13// it takes a function as an argument14numbers.reduce((total, current) => total + current, 0)15// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This function is passed as an argument1617// Example 4: multiplier() is a higher-order function because18// it returns a function19function multiplier(factor) {20 return number => number * factor; // <- Returns a function21}2223// Example 5: compose() is a higher-order function because it:24// 1. Takes two functions as arguments (f and g)25// 2. Returns a new function26const compose = (f, g) => x => f(g(x));2728// Example 6: debounce() is a higher-order function because it:29// 1. Takes a function as an argument (func)30// 2. Returns a new function31function debounce(func, delay) {32 return function(...args) { ... } // <- Returns a function33}