Java Reference
In-Depth Information
function name
function parameter
function convertToCentigrade ( degF ahren )
{
var degCent;
code that executes when
the function is called
degCent = 5/9 * (degF ahren - 32 );
return degCent;
}
Figure 3-13
You've probably already realized what this function does and how the code works. Yes, it's the infa-
mous Fahrenheit-to-centigrade conversion code again.
Each function you defi ne in JavaScript must be given a unique name for that particular page. The name
comes immediately after the
function
keyword. To make life easier for yourself, try using meaningful
names so that when you see it being used later in your code, you'll know exactly what it does. For example,
a function that takes as its parameters someone's birthday and today's date and returns the person's age
could be called
getAge()
. However, the names you can use are limited, much as variable names are. For
example, you can't use words reserved by JavaScript, so you can't call your function
with()
or
while()
.
The parameters for the function are given in parentheses after the function's name. A parameter is just
an item of data that the function needs to be given in order to do its job. Usually, not passing the required
parameters will result in an error. A function can have zero or more parameters, though even if it has
no parameters, you must still put the open and close parentheses after its name. For example, the top of
your function defi nition must look like the following:
function myNoParamFunction()
You then write the code, which the function will execute when called on to do so. All the function code
must be put in a block with a pair of curly braces.
Functions also give you the ability to return a value from a function to the code that called it. You use
the
return
statement to return a value. In the example function given earlier, you return the value of
the variable
degCent
, which you have just calculated. You don't have to return a value if you don't want
to, but you should always include a
return
statement at the end of your function, although JavaScript is
a very forgiving language and won't have a problem if you don't use a
return
statement at all.
When JavaScript comes across a
return
statement in a function, it treats it a bit like a
break
statement
in a
for
loop — it exits the function, returning any value specifi ed after the
return
keyword.
You'l l probably fi nd it useful to build up a “library” of functions that you use frequently in JavaScript
code, which you can cut and paste into your page whenever you need them.
Having created your functions, how do you use them? Unlike the code you've seen so far, which executes
when JavaScript reaches that line, functions only execute if you ask them to, which is termed
calling
or