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

function

The function statement defines a JavaScript function. It has the following syntax:

function funcname([arg1 [,arg2 [..., argn]]]) {
    statements
}

funcname is the name of the function being defined. This must be an identifier, not a string or an expression. The function name is followed by a comma-separated list of argument names in parentheses. These identifiers can be used within the body of the function to refer to the argument values passed when the function is invoked.

The body of the function is composed of any number of JavaScript statements, contained within curly braces. These statements are not executed when the function is defined. Instead, they are compiled and associated with the new function object for execution when the function is invoked with the ( ) function call operator. Note that the curly braces are a required part of the function statement. Unlike statement blocks used with while loops and other statements, a function body requires curly braces, even if the body consists of only a single statement.

A function definition creates a new function object and stores that object in a newly created property named funcname. Here are some example function definitions:

function welcome( ) { alert("Welcome to my home page!"); } function print(msg) { document.write(msg, "<br>"); } function hypotenuse(x, y) { return Math.sqrt(x*x + y*y); // return is documented below } function factorial(n) { // A recursive function if (n <= 1) return 1; return n * factorial(n ...
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