return (Statement)

Returns control back to the caller of a function.

Availability:

ECMAScript edition - 2
JavaScript - 1.0
JScript - 1.0
Internet Explorer - 3.02
Netscape - 2.0
Netscape Enterprise Server - 2.0
Opera - 3.0
JavaScript syntax:-return(anExpression);
-return anExpression;
-return;
Argument list:anExpressionA value to return to the function caller

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.

Warnings:

return

"A very long string goes here ...";

Example code:

   // 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();

See also:break, Completion type, continue, function( ... ) ..., Iteration statement, Jump statement, Statement

Cross-references:

ECMA 262 edition 2 - section - 12.9

ECMA 262 edition 3 - section - 12.9

Wrox Instant JavaScript - page - 27