Recipe 1.11 Obtaining the Result of a Function

1.11.1 Problem

You want to perform a function and return the results to the script that invoked the function.

1.11.2 Solution

Use a return statement that specifies the value to return.

1.11.3 Discussion

The return statement, when used without any parameters, simply terminates a function. Technically, return returns the value undefined to the caller if no value is specified. Likewise, if there is no return statement, the function returns undefined when it terminates. But any value specified after the return keyword is returned to script that invoked the function. Usually, the returned value is stored in a variable for later use:

function average (a, b) {   // Return the average of a and b.   return (a + b)/2; } var playerScore ; // Call the average(  ) function and store the result in a variable. playerScore = average(6, 12); // Use the result in some way. trace("The player's average score is " + playerScore);

You can use the return value of a function, without storing it in a variable, by passing it as a parameter to another function:

trace("The player's average score is " + average(6, 12));

Note, however, that if you do nothing with the return value of the function, the result is effectively lost. For example, this statement has no detectable benefit because the result is never displayed or used in any way:

average(6, 12);


ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net