Section 6.15. return


6.15. return

As you'll recall, a function invocation using the ( ) operator is an expression. All expressions have values; the return statement specifies the value returned by a function, which is thus the value of the function-invocation expression. Here's the syntax of the return statement:

 return expression; 

A return statement may appear only within the body of a function. It is a syntax error for it to appear anywhere else. When the return statement is executed, expression is evaluated and returned as the value of the function. Execution of the function stops when the return statement is executed, even if there are other statements remaining in the function body. The return statement can be used to return a value like this:

 function square(x) { return x*x; } 

The return statement may also be used without an expression to simply terminate execution of the function without returning a value. For example:

 function display_object(obj) {     // First make sure our argument is valid     // Skip the rest of the function if it is not     if (obj == null) return;     // Rest of function goes here... } 

If a function executes a return statement with no expression, or if it returns because it reaches the end of the function body, the value of the function-call expression is undefined.

Because of JavaScript's automatic semicolon insertion, you may not include a line break between the return keyword and the expression that follows it.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

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