Javascript functions can be written in a number of different ways.

Function declarations

Firstly we have the ‘classic’ named function:

function eatLead(){
  // do something
}
// and the call
eatLead();

This technique is known as a ‘function declaration’.

JSFIDDLE Demo

Function Expressions

Then we have the anonymous function:

document.getElementById('myButton').addEventListener('click', function(){
  // do something
});

The above function has no name and is associated with an event. This technique is a type of ‘function expression’.

JSFIDDLE Demo

We can also create a function expression by assigning it to a variable:

var eatLead = function() {
    // do something
}

The function still needs to be invoked with:

eatLead();

JSFIDDLE Demo

Functions defined via Functions Expressions can be named or anonymous. A named variant would be:

var fire = function eatLead() {
    // do something
}

JSFIDDLE Demo

Note that eatLead() is undefined outside the scope of the eatLead() function. This won’t work:

var fire = function eatLead() {
    // do something
}
document.getElementById('display').innerHTML = eatLead();
//eatLead() is undefined outside the scope of eatLead()

JSFIDDLE Demo

Functions can also be self invoking with the addition of some parenthesis.

//self invoking function expression
(function() {
    // do something
})();

Notice how this self invoking function is placed in parenthesis as function expressions cannot start with the keyword function. It is the second pair of brackets at the end that call the function.

JSFIDDLE Demo

If we wanted to send some parameters to the self-invoking function then we can do that to:

//self invoking function expression
(function(cheese) {
    alert(cheese);
})('cheddar');

JSFIDDLE Demo

We can have named self-invoking functions. You might need one of these if the function’s logic requires it to call itself, for example:

var cheeseCounter = 0;
(function eatCheese(cheese) {
    document.getElementById('display').innerHTML += cheese;
    cheeseCounter++;
    if(cheeseCounter < 10){
        eatCheese(' more, ');
    }
})('cheddar');

JSFIDDLE Demo

Using jQuery with a self-invoking function

A common trick with jQuery is to use the self-invoking function style and feed to it jQuery as a parameter.

(function($){
    // do something
})(jQuery)

The benefit of this is that the $ sign is internal to the self-invoked function so it leaves the potential to use other libraries … if you really felt the need to.

Leave a Comment