start page | rating of books | rating of authors | reviews | copyrights

Book HomeActionScript: The Definitive GuideSearch this book

9.4. Exiting and Returning Values from Functions

Unless instructed otherwise, a function will end naturally when the interpreter finishes executing the last statement in the function's body. You can, however, terminate a function before the last statement is reached. Additionally, a function can return a result (send back a calculated value) to the code that invoked it. Let's see how these things work.

9.4.1. Terminating a Function

The return statement, which was introduced in Chapter 6, "Statements", 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 function. Consider this example:

function say(msg) {
  return;
  trace(msg);         // This line is never reached
}

The preceding 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 normally the last statement in a function body unless it is used inside a conditional statement. In this example, we use return to exit if the password is not correct:

var correctPass = "cactus";
function enterSite(pass) {
  if (pass != correctPass) {
    // Exit if the password is wrong
    return;
  }
  // This code is reached only if the password is correct
  gotoAndPlay("intro");
}

enterSite("hackAttack");  // Function will exit prematurely
enterSite("cactus");      // Function will end naturally

As its name implies, return tells the interpreter to return to the location of the function invocation. If no return statement is present, ActionScript acts as if the last line of the function body contains a return statement:

function say(msg) {
  trace(msg);
  return;              // This line is completely optional in this context
}

Regardless of whether the return statement is implied or explicit, whenever a function terminates, execution resumes at the line of code following the function-call statement. For example:

say ("Something");  // This executes the code in the say( ) function
// Execution resumes here after the say( ) function terminates
trace ("Something else");

9.4.2. Returning Values from Functions

As we've seen, return always terminates a function. But it can also be used to send a value back to the script that invoked the function, using the following syntax:

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
}

When creating a function that is supposed to return the result of a calculation, don't forget to include a return statement that actually returns the desired value. Otherwise, the return value will be undefined and any subsequent calculations based on that result will almost certainly be incorrect.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.