What are first-class functions and higher-order functions?
Quick Answer
First-class functions means functions are values — you can store them in variables, put them in arrays/objects, pass them as arguments, and return them. A higher-order function is one that takes a function as an argument and/or returns a function — map, filter, reduce, addEventListener, a debounce wrapper.
First-class functions is the property that functions are just another kind of value in the language — I can assign a function to a variable, stick it in an array, pass it into another function, or return it. A higher-order function is one that takes advantage of that: it either accepts a function as a parameter or hands one back. Array.map is the everyday example — you pass it a function. A function that returns a configured function, like a debounce helper, is also higher-order. It's what makes callbacks and function composition possible.
- First-class is the language capability; higher-order is a function that uses it.
- Enables callbacks, composition, currying, and configurable behaviour (pass a comparator to
sort). - C# has the same via delegates /
Func/Actionand LINQ.