What is a higher order function?
In JavaScript, a higher-order function is a function that takes one or more functions as arguments, or returns a function as output. These functions are a powerful feature of the language that allow you to write concise and expressive code.
The best way to learn higher order functions (and likely the most “real-world”) is to look at “map()” and “filter()”. Both take functions as arguments where the function is applied to each element in an array.
- Map
For example, consider the map
function, which is used to apply a function to each element of an array and return a new array containing the results.
The map
function is a higher-order function because it takes a function as its argument, in this case the function to apply to each element of the array.
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(x => x * x);
- Filter
Another common higher-order function is filter
, which is used to select elements from an array based on a certain criteria. The filter
function takes a function as its argument, which is used to test each element of the array. Here’s an example of using filter
to select only the even numbers from an array:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]
- Reduce
The reduce() function can be used to combine all elements of an array into a single value.
Higher order functions can be combined with other functional programming concepts such as currying and partial application to create powerful abstractions and improve code reusability.