First-Class Citizen
Higher-order functions (HOFs) let you use functions as data, allowing for FP's most powerful patterns. (5 min. read)
We'll cover the following...
Higher-Order Functions
Functions operate on data, right?
Strings are data
Numbers are data
Booleans are data
Objects are data
Arrays are data
These 5 types are considered first-class citizens in every mainstream language.
What makes them first-class? You can pass them around, store them in variables and arrays, use them as inputs for calculations. You can use them like any piece of data.
Functions Can Be Data Too
JavaScript took a page from the FP book and added a sixth first-class citizen: functions.
See how filter uses isEven to decide what numbers to keep? isEven, a function, was a parameter to another function.
You can also return a function.
addNumbers needs two parameters, but doesn’t require them both at once. You can supply them immediately:
Or one by one:
A function that takes and/or returns another function is called a higher-order function. It’s “higher-order” because it operates on functions, in addition to strings, numbers, arrays, etc. Pretty meta.
This is only possible because JavaScript made functions first-class like strings, bools, objects, arrays, etc.
With functions, you can
- Store them as variables
- Insert them into arrays
- Assign them as object properties (methods)
- Pass them as arguments
- Return them from other functions
Like any other piece of data. That’s the key here.
Summary
-
Strings, numbers, bools, arrays, and objects can be stored as variables, arrays, and properties or methods.
-
JavaScript treats functions the same way.
-
This allows for functions that operate on other functions–higher-order functions.