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 ofa
andb
. return (a + b)/2; } var playerScore ; // Call theaverage( )
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);
Get Actionscript Cookbook 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.