Visit Mozilla.org

Core JavaScript 1.5 Reference:Operators:Special Operators:function Operator

From MDC


Contents

[edit] Summary

The function operator defines a function inside an expression.

Operator
Implemented in: JavaScript 1.5

[edit] Syntax

function [name]([param1, param2, ..., paramN]) {
   statements
}

[edit] Parameters

name 
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
paramN 
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

A function expression is very similar to and has almost the same syntax as a function declaration (see function for details). See Functions for information on the differences between function statements and function expressions.

[edit] Examples

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

var x = function(y) {
   return y * y;
};

The next example declares array a as an array of three functions:

var a = [
   function(y) {
      return y;
   }
   ,
   function(y) {
   {
      return y * y;
   }
   ,
   function (y) {
      return y * y * y;
   }
];

For this array, a[0](5) returns 5, a[1](5) returns 25, and a[2](5) returns 125.

[edit] See also

Functions, Function, function statement