Maria: Well, no. It works.
Professor: It works all right, but there’s something fundamentally wrong with it.
Imagine a more elaborate example when you write a function that computes and prints
the arithmetic mean of an arra y of numbers. Would such a function be u seful?
Mike: Maybe not so much. For example, if you only want to compute the arithmetic
mean and then do something else with it, n ot print it, then that function would be
completely useless.
Professor: Precisely. O ne of the important programm ing skills is to be able to write
functions that don’t do more th an one otherwise independent task in a single package.
Giving your functions descrip tive names is of great help in managin g that. As soon as
you discover th at a name hints at two different and generally independent tasks, make
two functions. For exam ple, the name writeLarger indicates that the function does
two things—it determines w hich value is larger and w rites that value to the browser
window.
Another ad vantage of using descriptive names for fun ctions is that your code will be
more readable and thus easier to maintain.
Mike: I guess that the rules for naming fun ctions are generally the same as they are
for variables.
Professor: That’s right. You may use any legal JavaScript identifier as a function
name so long as it is not a reserved keyword.
Maria: Bu t if a function doesn’t write out what it compute s, then I think it should at
least be able to return the computed value, shouldn’t it?
Professor: Exactly. You can u se the return keyword to accomplish that. The value
of the expression that you associate with retu rn is the return value of the function.
If you don’t use return inside the function b ody—or you u se return without any
expression—then the function returns the undefined value. Note that you can put
return anywhere inside the function body a nd not just at the end—the function will
stop its execution and return as soon as the retur n keyword is reached.
Let’s now split the above writeLarger() function into two independe nt functions.
The first one determines and returns the larger of two arguments, and the other simply
writes out the value of the passed argument:
var larger = function(x, y) {
return x > y ? x : y;
};
var write = function(x) {
document.write(x);
};
The first function returns the value of the expression that app ears afte r the return
keyword. In order to write the larger of two values to the browser window, we may
192 Meeting 10. Understa nding Functions