Exiting and Returning Valuesfrom 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.

Terminating a Function

The return statement, which was 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 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 ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.