invoke both functions in the following manner:
write(larger(5, 13)); //Writes 13
The following figur e shows how both functions are executed .
larger(5, 13);
Main Program
write(
13
5
13
13
document.write(x);
Functions
);
x
y
x
return x > y ? x : y;
The function larger() is called first and it returns 13, which is the value of the
expression x > y ? x : y. This value is immediately used as an argument of the
function write(), which is called next and w rites the value to the browser window.
Maria: I don’t see why w rite(), which only calls documen t.write(), is usefu l.
Professor: Later you may decide to c hange how you write things out, in which case
it is very convenient that you already h ave a function defined for writing. That way,
you don’t h ave to change the cod e all over your program, but you only have to rewrite
a single function definition. Sometimes a function like that is called a p laceholder
because you define it primarily to replace it later with different code.
Mike: What happens if you provide a different number of arguments when you call a
function? We learned, for example, that a number of arguments passed to a Date()
constructo r decides about what a constructor actually does. Can we also implement
behavior like that in our fu nctions?
Professor: JavaScript won’t mind if you invoke a function with either fewer or more
arguments than de clared parameters. It’s the programmer’s responsibility to handle
those situations.
If you provide fewer arguments than declared parameters, then the missing arguments
are assumed to have the undefined value. You can use that fact to write a fu nction
that accepts op tional para meters. For example, we can write a fun ction that returns a
Euclidean norm of either a real numbe r or a two-dimensional vector, depending upon
the number of passed arguments. In n ot-so-mathematical language that m eans the
function returns either the absolute value of a real nu mber or the length of a vector. The
10.2. Writing Function Definitions 193