5.11 functionEarlier, we saw that the () operator is used to invoke a function. Before a function can be invoked, however, it must be defined (except for those that are predefined by JavaScript); the function statement is used to define a new function. It has the following syntax:
function funcname([arg1 [,arg2 [..., argn]]]) { statements } funcname is the name of the function that is being defined. This must be a literal name, not a string or an expression. arg1, arg2, and so on to argn are a comma-separated list of any number (including zero) of argument names for the function. These are also literal names, not strings or expressions. These names can be used as variables within the body of the function; when the function is executed, they will be assigned the values specified in the function call expression. The function statement differs from statements like the while and for loops. In those loops, the body of the loop is a single statement, which can be a single primitive statement or a block of statements enclosed in curly braces. For the function statement, however, curly braces are a required part of the syntax, and any number of JavaScript statements may be contained within. Even if the body of a function consists of only a single statement, the curly braces must still be used. 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; else return n * factorial(n - 1); } The most important way that the function statement differs from other statements is that the statements that form the body of the function are not executed. Instead, they are stored as the definition of a new function named funcname, and may be executed at any later time with the () function call operator. We'll learn more about functions in Chapter 6, Functions. |
|