1.11. Obtaining the Result of a Function
Problem
You want to perform a function and return the results to the script that invoked the function.
Solution
Use a return statement that specifies the value
to return.
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);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access