home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

6.15. return

As you'll recall, invoking a function with the ( ) operator is an expression. All expressions have values; the return statement is used to specify the value returned by a function. This value is the value of the function invocation expression. The syntax of the return statement is:

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.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.