return expression;
The value of expression becomes the result
of the function invocation. For example:
// Define a function that adds two numbers
function combine(a, b) {
return a + b; // Return the sum of the two arguments
}
// Invoke the function
var total = combine(2, 1); // Sets total to 3
The expression or result returned by the return
statement is called the return value of the
function.
Notice that our combine( ) function merely
calculates and returns the sum of two numbers (it will also
concatenate two strings). It does not perform an action, as did the
sayHi( ) function (which displayed a message) or
the moveClip( ) function (which repositioned a
movie clip). We can make use of a function's return value by
assigning it to a variable:
var total = combine (5, 6); // Sets total to 11
var greet = combine ("Hello ", "Cheryl") // greet is "Hello Cheryl"
The result of a function call is just an ordinary expression.
Therefore, it can also be used in additional expressions. This
example sets phrase to "11 people were at
the party":
var phrase = combine(5, 6) + " people were at the party";
We'll frequently use function return values as parts of
compound expressions -- even as arguments in another function
invocation. For example:
var a = 3;
var b = 4;
function sqr(x) { // Squares a number
return x * x;
}
var hypotenuse = Math.sqrt(sqr(a) + sqr(b));
Notice how the example passes the return values of our sqr(
) function to the Math.sqrt( )
function! Along the same lines, our earlier example could be
rewritten as:
var phrase = combine (combine(5,6), " people were at the party");
In the preceding example, the expression
combine(5,6), which evaluates to 11, becomes an
argument to the outer combine( ) function call,
where it is concatenated with the string " people were at the
party".
If a return statement doesn't include an
expression to be returned or the return
statement is omitted entirely, a function will return the value
undefined. In fact, this is a common source of
error. For example, the following won't do anything meaningful
because the return statement is missing:
function combine(a, b) {
var result = a + b; // The result is calculated, but not returned
}
Likewise, this too is incorrect:
function combine(a, b) {
var result = a + b;
return; // You've forgotten to specify the return value
}