
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Exiting and Returning Values from Functions
|
189
trace("The name is " + first + " " + middle + " " + last);
}
Exiting and Returning Values
from Functions
Unless instructed otherwise, a function will end naturally when the interpreter fin-
ishes executing the last statement in the function’s body. You can, however, termi-
nate a function before the last statement is reached. Additionally, a function can
return a result (send back a value) to the code that invoked it. Let’s see how these
things work.
Terminating a Function
The return statement, which we introduced in Chapter 6, can be used to terminate a
function and, optionally, to return a result. When the interpreter encounters a return
statement during a function execution, it skips any remaining statements in the func-
tion. Consider this example:
function say (msg) {
return;
trace(msg); // This line is never reached
}
This example is not realistic, because its return statement always causes the function
to end before the trace() statement is reached. Therefore, the return statement is nor-
mally the last statement in a function body, unless it is used inside a conditional
statement. In the following example, we use return to exit the function if the pass-
word is not correct:
var correctPass = "cactus";
function enterSite(pass) {
if (pass ...