function

Did you know that you can read content offline by using one of these tools? If you would like to read offline MDN content in another format, let us know by commenting on Bug 665750.

Dash App
  • Tags
  • Files

 

Summary

Declares a function with the specified parameters.

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

Version Information

Statement
Implemented in JavaScript 1.0
ECMAScript Edition ECMA-262

Syntax

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

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.

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.

Examples

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;
}

See also

Functions, Function, function operator