Higher Order Functions
Functions are like any other variables in JavaScript, making them first-class citizens. They can be operated upon, returned, passed as an argument just like any other conventional variable. A higher-order function takes another function as an argument and returns a function or a result. What if we say, you’ve seen a higher-order function in this article already?
1const findFruit = (basket) => {
2 const fruits = basket.filter(item => item.type == "fruit");
3 return fruits;
4}
Remember this example from above? The filter()
method is a higher-order function that has an anonymous function at the beginning that accepts each item in the basket as an argument and checks for its type. The filter
method then uses the return value from that to add elements to the basket that satisfy this equality.
Other examples of higher-order functions are forEach()
, map()
and reduce()
. Higher-order functions promote reusability in our code, helps to isolate actions or abstract them, perform function composition, etc.