abstract. Let’s take the next step in abstract thinking and consider functions as sub‐
routines that return a value.
Our
printLeapYearStatus
is nice, but as we build out our program, we quickly grow
out of logging things to the console. Now we want to use HTML for output, or write
to a file, or use the current leap year status in other calculations, and our subroutine
isn’t helping with that. However, we still don’t want to go back to spelling out our
algorithm every time we want to know whether it’s currently a leap year or not.
Fortunately, it’s easy enough to rewrite (and rename!) our function so that it’s a sub‐
routine that returns a value:
function
isCurrentYearLeapYear
() {
const
year
=
new
Date
().
getFullYear
();
if
(
year
%
4
!==
0
)
return
false
;
else
if
(
year
%
100
!=
0
)
return
true
;
else
if
(
year
%
400
!=
0
)
return
false
;
else
return
true
;
}
Now let’s look at some examples of how we might use the return value of our new
function:
const
daysInMonth
=
[
31
,
isCurrentYearLeapYear
()
?
29
:
28
,
31
,
30
,
31
,
30
,
31
,
31
,
30
,
31
,
30
,
31
];
if
(
isCurrentYearLeapYear
())
console
.
log
(
'It is a leap year.'
);
Before we move on, consider what we’ve named this function. It’s very common to
name functions that return a boolean (or are designed to be used in a boolean con‐
text) with an initial
is
. We also included the word current in the function name; why?
Because in this function, it’s explicitly getting the current date. In other words, this
function will return a different value if you run it on December 31, 2016, and then a
day later on January 1, 2017.
Functions as…Functions
Now that we’ve covered some of the more obvious ways to think about functions, it’s
time to think about functions as…well, functions. If you were a mathematician, you
would think of a function as a relation: inputs go in, outputs come out. Every input is
related to some output. Functions that adhere to the mathematical definition of the
function are sometimes called pure functions by programmers. There are even lan‐
guages (such as Haskell) that allow only pure functions.
How is a pure function different than the functions we’ve been considering? First of
all, a pure function must always return the same output for the same set of inputs.
isCurrentYearLeapYear
is not a pure function because it will return something dif‐
ferent depending on when you call it (one year it may return
true
, while the next year
Functions as…Functions | 185