Skip to Main Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced content levelIntermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
Coding with JavaScript For Dummies

Coding with JavaScript For Dummies

Chris Minnick, Eva Holland

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata