• Use functions as properties of an object (see
• Pass a function into a function.
• Return a function from a function.
• Return a function from a function that itself takes a function as an argument.
Is your head spinning yet? Written out this way, it does seem incredibly abstract, and
you might reasonably be wondering “Why on earth would you want to do that?” The
fact is, this flexibility is incredibly powerful, and all of these things are done quite fre‐
quently.
Let’s start with the most comprehensible item on that list: aliasing a function. Imagine
you have a function with an incredibly long name and you want to use it multiple
times within a few lines, and it’s getting exhausting typing it, and it results in code
that’s very hard to read. Because a function is just a data type like any other, you can
create a new variable with a shorter name:
function
addThreeSquareAddFiveTakeSquareRoot
(
x
) {
// this is a very silly function, isn't it?
return
Math
.
sqrt
(
Math
.
pow
(
x
+
3
,
2
)
+
5
);
}
// before
const
answer
=
(
addThreeSquareAddFiveTakeSquareRoot
(
5
)
+
addThreeSquareAddFiveTakeSquareRoot
(
2
))
/
addThreeSquareAddFiveTakeSqureRoot
(
7
);
// after
const
f
=
addThreeSquareAddFiveTakeSquareRoot
;
const
answer
=
(
f
(
5
)
+
f
(
2
))
/
f
(
7
);
Note that in the “after” example, we don’t use parentheses
after
addThreeSquareAddFi
veTakeSquareRoot
. If we did, we would be invoking the function, and
f
—instead of
being an alias of
addThreeSquareAddFiveTakeSquareRoot
—would contain the result
of invoking it. Then when we tried to use it like a function (
f(5)
, for example) it
would result in an error because
f
wouldn’t be a function, and you can only invoke
functions.
This is a completely contrived example, of course, and something you don’t really see
that often. Where it does come up, however, is in namespacing, which is common in
Node development (see
). For example:
const
Money
=
require
(
'math-money'
);
// require is a Node function to
// import a library
const
oneDollar
=
Money
.
Dollar
(
1
);
// or, if we don't want to have to say "Money.Dollar" everywhere:
const
Dollar
=
Money
.
Dollar
;
const
twoDollars
=
Dollar
(
2
);
// note that oneDollar and twoDollars are instances of the same type
192 | Chapter 13: Functions and the Power of Abstract Thinking