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’.
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’.
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();
Functions defined via Functions Expressions can be named or anonymous. A named variant would be:
var fire = function eatLead() { // do something }
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()
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.
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');
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');
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.