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 ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.