Javascript mozilla functions

Description

Every function in JavaScript is a Function object .

See Function for information on properties and methods of Function objects .

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

A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter.

For all other functions, the default return value is undefined.

The parameters of a function call are the function’s arguments.

Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object’s properties, that change is visible outside the function, as shown in the following example:

Defining functions

anonymous function

Here is an example of an anonymous function expression (the name is not used):

var myFunction = function() {
    statements
}

It is also possible to provide a name inside the definition in order to create a named function expression:

named function expression

var myFunction = function namedFunction(){
    statements
}

One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

IIFE (Immediately Invokable Function Expression)

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression) .

(function() {
    statements
})();

IIFE are function expressions that are invoked as soon as the function is declared .