Returning values from functions

You use the return statement to return values from functions. The return statement specifies the value that is returned by a function. The return statement returns the result of an evaluation as a value of the function in which an expression executes. The return statement returns its result immediately to the calling code.

For more information, see return statement in the ActionScript 2.0 Language Reference.

The following rules govern how to use the return statement in functions:

For example, the following function returns the square of the parameter myNum and specifies that the returned value must be a Number data type:

function sqr(myNum:Number):Number {
  return myNum * myNum;
}

Some functions perform a series of tasks without returning a value. The next example returns the processed value. You are capturing that value in a variable, and then you can use that variable within your application.

To return a value and capture it in a variable:

  1. Create a new Flash document and save it as return.fla.
  2. Add the following code to Frame 1 of the main Timeline:
    function getArea(width:Number, height:Number):Number {
         return width * height;
    }
    

    The getArea() function takes two parameters, width and height.

  3. Type the following code after the function:
    var area:Number = getArea(10, 12);
    trace(area); // 120
    

    The getArea() function call assigns the values 10 and 12 to the width and height, respectively, and you save the return value in the area instance. Then you trace the values that you save in the area instance.

  4. Select Control > Test Movie to test the SWF file.

    You see 120 in the Output panel.

    The parameters in the getArea() function are similar to values in a local variable; they exist while the function is called and cease to exist when the function exits.


Flash CS3