By passing an arbitrary function into
sum
, we can make it do…well, anything we
want. Need the sum of square roots? No problem. Need the sum of the numbers
taken to the 4.233 power? Simple. Note that we want to be able to call
sum
without
doing anything special…meaning there is no function. Inside the function, the
parameter
f
will have the value
undefined
, and if we tried to invoke it, it would cause
an error. To prevent this, we turn anything that isn’t a function into the “null func‐
tion,” which, in essence, does nothing. That is, if you pass it
5
, it returns
5
, and so on.
There are more efficient ways we could have handled this situation (such as invoking
a different function without the overhead of invoking the null function on every ele‐
ment), but it’s good practice to see “safe” functions created this way.
Return a Function from a Function
Returning a function from a function is perhaps the most esoteric usage for func‐
tions, but is extremely useful. You can think of returning a function from a function
like a 3D printer: it’s a thing that does something (like a function) that can, in turn,
make something that also does something. And the exciting part is that the function
you get back can be customized—much like you can customize what you print from a
3D printer.
Let’s consider our
sum
function from earlier that takes an optional function to operate
on each element before summing it. Remember how we said we could create a sepa‐
rate function called
sumOfSquares
if we wanted to? Let’s consider the situation in
which we need such a function. Specifically, a function that takes an array and a func‐
tion is not good enough: we explicitly need a function that takes only an array and
returns the sum of squares. (If you are wondering when such a circumstance might
arise, consider an API that allows you to provide a
sum
function, but only accepts
functions that take a single argument.)
One approach would be to create a new function that simply calls our old function:
function
sumOfSquares
(
arr
) {
return
sum
(
arr
,
x
=>
x
*
x
);
}
While this approach is fine, and may work if all we need is the one function, what if
we need to be able to repeat this pattern over and over? A solution to our problem
might be creating a function that returns a specialized function:
function
newSummer
(
f
) {
return
arr
=>
sum
(
arr
,
f
);
}
This new function—
newSummer
—creates a brand new
sum
function that has only one
argument, but uses a custom function. Let’s see how we might use it to get different
kinds of summers:
Function Variables | 195