Declaration syntax: function name(var1, var2, ...) { ... }
Expression syntax: function (var1, var2, ...) { ... }


A function is a block of code in a script which performs a specific task. Functions can take parameter values which can be used throughout the function's execution.

Once defined, functions can be called in other places in the script, potentially multiple times. Doing so allows the scripter to:

As a declaration

When declaring a function, you MUST give it a name, and you may give it a set of parameter variables to accept. e.g.

function example()
	return 5;

In this example, a new function example() is defined.

To accept function parameters, you can give a list of temporary variable names which will take the parameters:

function example(, temp.two)
	return + temp.two;

In this example, the function example() actually takes two values and adds them together. You can call the function giving it values like this:

example(3, 2);

... which will return 5.

As an expression

When writing a function as an expression, you MUST NOT give it a name, and you may give it a set of variables to accept. e.g.

f = function () { return 5; };

When written as expressions, functions are "first-class". This means that you can pass a function to another function as if it were a value (for more detail, see Intro to anonymous functions).

Related articles

The following related articles are also recommended:



There are no comments on this page. [Add comment]

Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki