HTML and CSS Reference

In-Depth Information

Figure 10-20

complete list of e-mail address links

Creating a Function to Return a Value

You created the showEM() function to perform the action of writing a text string to your

Web document. The other use of a function is to return a calculated value. For a function

to return a value, it must include a
return
statement as follows:

functionƒ
function_name
(parameters){

ƒƒƒJavaScriptƒcommands

ƒƒƒreturnƒ
value
;

}

where
value
is the calculated value that is returned by the function. For example, the

following CalcArea() function calculates the area of a rectangular region by multiplying

the region's length and width:

functionƒCalcArea(length,ƒwidth)ƒ{

ƒƒƒvarƒareaƒ=ƒlength*width;

ƒƒƒreturnƒarea;

}

In this function, the value of the area variable is returned by the function. You can call

the function to retrieve this value. The following code uses the function to calculate the

area of a rectangle whose dimensions are 8 × 6 units:

varƒxƒ=ƒ8;

varƒyƒ=ƒ6;

varƒzƒ=ƒCalcArea(x,y);

The first two commands assign the values
8
and
6
to the x and y variables, respec-

tively. The values of both of these variables are then sent to the CalcArea() function as the

values of the length and width parameters. The CalcArea() function uses these values to

calculate the area, which it then returns, assigning that value to the z variable. As a result

of these commands, a value of 48 is assigned to the z variable.

Functions that return a value can be placed within larger expressions. For example,

the following code calls the CalcArea() function within an expression that multiplies the

area value by 2:

varƒzƒ=ƒCalcArea(x,y)*2;