The functions are objects that are used to specify or encapsulate one or more statements.

They are widely used in JavaScript because once interpreted by a parsing mechanism, a function may be run from any place inside a script and at any time. That makes them very suitable for those groups of statements that have to be executed multiple times and by multiple objects within a script.

The functions are declared by using function keyword, followed by the name of it (with or without arguments) and the body of it (statement).

Syntax

The basic function declaration syntax looks like this:

function myFunction(argument_0, argument_1, ? argument_N) {

   statement1;

   statement2;

}

The function above may be called simply by using its name from anywhere within the software, like this:

myFunction(arg0, arg1);

The arguments are optional, but when they are passed to a function and are more than one, they must be separated by commas.

The apprentices {} may be skipped if the function contains only one statement, for instance:

function helloWorld() alert("Hello World!");

Return values

By using a return statement a function may return a value. Although that approach is not needed, it is very useful in programming. In such a manner, that function's output may be assigned to a variable, as shown in this example:

function addNum(a, b) {

   return a + b;

}

var result = addNum(2, 5);

The variable "result" in the above example will contain number "7";

Function as expression

A function does not have to be declared always; for instance the above example may be written as an expression:

var result = function(a, b) {

   return a + b;

};// semi-colon is needed in case of an expression

A function may also be expressed by using the Function constructor, as shown here:

var result = new Function("a", "b", "return = a + b");

This approach is not recommended because it causes a double interpretation of the code and that affects performance.

NOTE: If a function is initialized as an expression, the statement must end with semicolon (;).

Declaration vs. expression

It is important to know that a declared functions get executed immediately, while those initialized through an expression will get executed regularly. Observe these examples:

var result = addNum(2, 5);

function addNum(a, b) {

   return a + b;

}

This code will execute normally because the function "addNum" will be interpreted before the normal flow begins running. However if we re-write it like this it will give us an error:

var result = addNum(2, 5);

var addNum = function(a, b) {

   return a + b;

};

The error happen because the function "addNum" will be called before it's initialized.

Example

Basic function declaration example:

 

›› go to examples ››