Just the weekly tutorials.

How to understand JavaScript anonymous (nameless) functions and their association with initializing the main jQuery object

Executing a Nameless Function

We know that JavaScript allows us to create functions that can have zero parameters and return nothing. But it is also possible to create a function that has no name (cannot be executed by calling it later, because functions are called by using their names, this is, however, an anonymous, nameless function.)

function(){ };

We just created an empty anonymous function. The following construct is often used by programmers to create a list of statements to be executed at the given time. But what is the given time? It could be, "right away," soon as it is created.

Simply creating an anonymous function won't really execute the function, only create it. However, there is one trick programmers use to create and execute anonymous functions right away. Let's discover what it is and how it can be used to help us understand efficient JavaScript code which sometimes can look outright confusing.

Enclosing JavaScript Statements Within Parentheses

We have to temporarily side-track into another subject before we go any further. It's a perfect place to talk about it now because it will help you understand how an anonymous function can be executed without referring to it by its name, later in this tutorial. Let's consider this JavaScript statement (learn more about javascript statements here):

"Hello"

It is a string. And we can perform string operations on it. For example the method substr() which belongs to the String object can crop out a set of characters from the string based on a specified length ranging between an arbitrary point a to point b within the string:

"Hello".substr(0, 2); // results in the first letter "He"

But what happens if we wrap it with parentheses? Would it not still work?

("Hello").substr(0, 2); // still results in "He"

This still works. Because wrapping a legal statement with parentheses doesn't break the code.

The above examples work and in each case the substr property of the String object is accessed. But an object of type String is different from an object of type Function. It's main difference is that a function can be executed, a string cannot be (of course, that would not make sense.)

In the same way (using the dot operator) we can access members of a function object, even if it is anonymous:

function(){}.prototype; // correctly results in [Object object]

But we are unable to execute an anonymous function by adding () to its end (in an attempt at executing it similarly to a named function using its name and () at the end):

function(){ }(); // syntax error!

The statement above is illegal and will not execute. We have just broken the rules of function expression syntax in JavaScript. In order to remedy the situation, we can wrap the anonymous function with parentheses as shown in the following example:

(function(){ }); // wrapped!

And only then attempt to execute it by adding () to the very end:

(function(){ })(); // now it works!

What happens here is that we first wrapped the anonymous function within a set of parentheses. This created a legal JavaScript statement, from another legal statement. Except we really needed those parentheses this time to circumvent the syntax error produced by {}() pattern (this is just against the rules of JavaScript and won't compile as legal code).

Once we wrapped the function, only then we executed it by appending the () to the end of the function. We used parentheses again, but this time for a completely different reason. The appended () lets JavaScript know that we want to execute a function. Same parentheses, different reasons.

Keep in mind that the first set of parentheses create a statement from the anonymous function. The second set of parentheses actually execute what was just defined as a statement. To further show what's going on here, let's create a nameless function which takes 2 parameters and returns their sum:

(function(a,b){ return a+b; })(1,2); // result is 3

Now this is a little more clear. We define a function with parameters a and b, and then we immediately execute it passing values 1 and 2 as its parameters. That's really what's going on here.

Interestingly, we can pass parameters to a function even if it does not ask for them:

(function(){ /*...*/ })(1,2);

But JavaScript functions have another trick up their sleeve(if they had one). It's to do with the argument property that all JavaScript functions can access from within themselves. They are explained in more detail in Life of JavaScript Function Properties article on this site. But briefly, let's take a look:

(function() { var a1 = arguments[0]; var a2 = arguments[1]; return a1 + a2; })(3,2); // result is 5

That's very interesting how we can work with function arguments that were passed to a JavaScript function, without having mentioned them in the function definition itself. Very clever, JavaScript.

Using a Function Closure to Create a jQuery Object

By going through all of these examples we have been slowly slipping into the territory of a new subject: function closures. An anonymous function can act as a function closure mechanism. The nameless function itself is not a closure, it is still just a function without a name. But a function closure is the mechanism that works with program scope. Specifically, it hides variables from the global scope by concealing them within the scope of the nameless function. There are many reasons for why we need this functionality. Let's take a look at one that has to do with jQuery.

Normally, as recommended by jQuery the code that deals with DOM elements and plugin initialization should go inside the following command:

$(document).ready(function(){ /* here */ });

This is fine and most people use it to initialize their plugins and do various other JavaScript inits.

The anonymous function is passed as an event method. It will be executed whenever the document object has finished loading (once absolutely all DOM elements are loaded into the web page, just before $(window).load event which will follow once all resources have finished downloading (images, etc.)

And perhaps after everything we have learned in this tutorial so far, the following construct often seen in jQuery initialization code will make a lot more sense:

(function(){ /* your jQuery code */ })(jQuery);

Knowing what you know now you can probably guess what's happening here. We just created an anonymous function, and passed the main jQuery object into it as the only parameter, which will now be accessible from within the function.

As you may know all functions have a local scope. It means variables created in (or passed into as arguments) a function will become available locally only within the scope of that function. Accessing them outside of the function will become impossible.

The purpose of starting your code within an anonymous function can isolate the jQuery object from the global scope (the rest of your program.) Programmers sometimes do this when using jQuery with other libraries, so their names won't clash. This construct is often referred to as a function closure.

Function Constructors, Declarations and Expressions in JavaScript

Understanding the difference between a function constructor, declaration and expression is fundamental to understanding anonymous(nameless) functions, how they work and when they can be executed.

From JavaScript's ECMA specification on page 83, section 13 "Function Definition" we learn that there are three ways in which a function(or an object of type Function) can be created.

Just the weekly tutorials.