A return keyword is a jump statement. It is used to unconditionally exit from a function, pass back a result, and make execution flow to the caller of the function.
When the return statement is executed, the execution context is disposed of and removed from the stack. Execution continues at the point in the caller where the function was invoked. The function is replaced by the value being returned.
If the function is not being assigned to an LValue or Left-Hand Side expression or has been cast to a void type, the result will be discarded.
If the expression is omitted in the return statement, the undefined value is returned in its place. While compiled languages are far more particular about the presence or absence of this expression, JavaScript is far more forgiving.
Functions that return undefined values are likely to be used as procedures rather than functions. A procedure is invoked as a statement that stands alone. The intent of a function is to return a result that will be substituted in its place.
It is considered illegal for the return statement to be present in any statement block other than that belonging to a function. However it can exist inside the statement block associated with a conditional statement or iterator statement as long as they themselves are within a function block. They may be nested more than one level deep but must ultimately belong to a function.
It is considered to be a syntax error to use the return statement anywhere other than in a function body.
You will not get the return value back properly if there is a line terminator between the return keyword and the value is was supposed to return. There is a temptation to break long strings over several lines like this:
return
"A very long string goes here ...";
This will return the value undefined and not the string you intended to return. It is probably better style to assign the string to a variable and return that but there are implications there of string construction-destruction, garbage collection, and potential memory leaks and to trade those problems off it's best to try and eliminate string creation and memory usage if possible.
// Declare a procedure with an implied return function aProcedure() { document.write("Hello"); } // Declare a procedure that returns an undefined value function anotherProcedure() { alert("Click OK to continue"); return; } // Declare a function that returns a result function aRealFunction() { return 1000; } // Use the functions and procedures aProcedure(); anotherProcedure(); x = aRealFunction();
ECMA 262 edition 2 - section - 12.9
ECMA 262 edition 3 - section - 12.9
Wrox Instant JavaScript - page - 27
Prev | Home | Next |
ResultSet.prototype | Up | returnValue |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |