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

JavaScript: The Definitive Guide

Previous Chapter 5

5.12 return

As you'll recall, function invocation with the () operator is an expression. All expressions have values, and 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 ];

When the return statement is executed, the 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 still 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
    // and skip rest of function if it is not.
    if (obj == null) return;
    // rest of the function goes here...

If a function executes a return statement with no expression, or if it never executes a return statement (i.e., it simply executes all the statements in the body and implicitly returns) then the value of the function call expression will be undefined (i.e., the special JavaScript undefined value).

It is a syntax error to use the return statement anywhere except in a function body.

Previous Home Next
function Book Index The Empty Statement

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell