Main Page

function

For example:
function sayHi(sName, sMessage) {
alert(“Hello “ + name + “,” + sMessage);
}
This function can then be called by using the function name, followed by the function arguments enclosed
in parentheses (and separated by commas, if there are multiple arguments). The code to call the
sayHi()
function looks like this:
sayHi(“Nicholas”, “how are you today?”);
This code results in the alert displayed in Figure 2-8.
Figure 2-8
The
sayHi()
function doesn’t specify a return value, but it requires no special declaration (such as
void
is used in Java) to do so. Likewise, a function doesn’t need to explicitly declare a return value type if the
function does indeed return a value. The function need only use the
return
operator followed by the
value to return:
function sum(iNum1, iNum2) {
return iNum1 + iNum2;
}
The value of the
sum
function is returned and assigned to a variable like this:
var iResult = sum(1,1);
alert(iResult); //outputs “2”
Another important concept is that, just as in Java, the function stops executing code after a
return
state-
ment is executed. Therefore, any code that comes after a
return
statement is not executed. For example,
the alert in the following function is never displayed:
function sum(iNum1, iNum2) {
return iNum1 + iNum2;
alert(iNum1 + iNum2); //never reached
}
It is possible to have more than one
return
statement in a function, as in this function:
function diff(iNum1, iNum2) {
if (iNum1 > iNum2) {
60
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 60


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7