Tag Archives: anonymous functions

Javascript functions

JavaScript allows numerous ways in which functions can be created and invoked.

Named functions

These have a name associated with them

function nameOfFuction(){ // code goes here; }

Assigned functions

These are usually named or anonymous functions which are assigned to a variable

var someName = function someFunction() { // code; };
// invoking the function like so
someName();

In this case the function is considered a statement so needs to have a semicolon unlike a typical function declaration.

Anonymous functions

These are functions without a name and are most suited for assignment to other variables, in fact the previous function type would be far better using anonymous functions.

var someName = function someFunction() { // code; };
// invoking the function like so
someName();

Another way anonymous functions can be used is by having it as the return value of another function

function mainFunction(param1, param2){   // code   return function(){
      // code 
   };}d

In order to utilise this, the main function itself will NOT work as it will only return the function statement it contains within its body. It is returned in a structure known as a closure:

 // This will return anonymous function from the main function body
mainFunction(paramValue1, paramValue2);
( function() { //code } )

It can, however, be assigned to a variable and thus run like an assigned function

var functionRunner = mainFunction(paramValue1, paramValue2);
functionRunner();

or it will need to have a pair of parenthesis added to the end of the function call if it is to be invoked like a standalone function, which will not be returning a function.

mainFunction(paraValue1, paramValue2)();

What is happening is that  the returned anonymous function will get the ‘()’ and be invoked like a regular function call. This is known as immediate function invocation.