Higher order
Higher order functions are functions that manipulate other functions. For example, a function can take other functions as arguments and/or produce a function as its return value. Such fancy functional techniques are powerful constructs available to you in JavaScript and other high-level languages like python, lisp, etc.
We will now create two simple functions, add_2
and double
, and a higher order function called map
. map
will accept two arguments, func
and list
(its declaration will therefore begin map(func,list)
), and return an array. func
(the first argument) will be a function that will be applied to each of the elements in the array list
(the second argument).
The functions in the above example are simple. However, when passed as arguments to other functions, they can be composed in unforeseen ways to build more complex functions.
For example, if we notice that we use the invocations map(add_2, ...)
and map(double, ...)
very often in our code, we could decide we want to create two special-purpose list processing functions that have the desired operation baked into them. Using function composition, we could do this as follows:
Now let's create a function called buildProcessor
that takes a function func
as input
and returns a func
-processor, that is, a function that applies func
to each input in list.
Let's look at another example.
We'll create a function called buildMultiplier
that takes a number x
as input and returns a function that multiplies its argument by x
:
Last updated