Visit Mozilla.org

Core JavaScript 1.5 Reference:Statements:function

From MDC


Contents

[edit] Summary

Declares a function with the specified parameters.

You can also define functions using the Function constructor and the function operator (function expression).

Statement
Implemented in: JavaScript 1.0, NES 2.0

JavaScript 1.5, NES 6.0: Added conditional function declarations (Netscape extension).

ECMA Version: ECMA-262

[edit] Syntax

function name([param] [, param] [..., param]) {
   statements
}

[edit] Parameters

name 
The function name.
param 
The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements 
The statements which comprise the body of the function.

[edit] Description

To return a value, the function must have a return statement that specifies the value to return.

A function created with the function statement is a Function object and has all the properties, methods, and behavior of Function objects. See Function for detailed information on functions.

A function can also be declared inside an expression. In this case the function is usually anonymous. See function operator for more information about the function (function expression).

Functions can be conditionally declared. That is, a function definition can be nested within an if statement. Technically, such declarations are not actually function declarations; they are function expressions.

[edit] Examples

[edit] Example: Using function

The following code declares a function that returns the total dollar amount of sales, when given the number of units sold of products a, b, and c.

function calc_sales(units_a, units_b, units_c) {
   return units_a*79 + units_b * 129 + units_c * 699;
}

[edit] See also

Functions, Function, function operator