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):


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:

    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.

  • Function Constructor is used when the function object is created with the new operator. The function constructor object conveniently named Function already pre-exists in JavaScript and we can readily start using it.

    The Function object is the constructor. By convention (but is not an absolute requirement) JavaScript object constructor names begin with a capital letter. For instance, Array for array constructor, String for string constructor, Function for function constructor, and so forth. Here is an example of creating a new Function object:

    var calc = new Function('a', 'b', 'c', 'return a * b / c;');

    Note that a multiple number of parameters and the function body itself (always the last or the only parameter) are entered directly into the constructor as its own parameters.

    First the parameter names, separated by a comma (as many as you need.) The last one is the function body itself.

    This function will simply multiply a by b and then divide the result by c: return a * b / c; and return the result. This is called the return value of a function. It’s optional to have one in any function and shown here only as an example of how to make one.

    We can now call this function by name using the following statement:

    calc(5, 20, 10); // will return 10

    Note that this function will return 10, because 5 times 20 (a * b) is 100. And then we divide it by 10 (a * b / c) which results in 10.

  • Function Declaration is a process that takes place when the function is created using the more common method of simply using the function keyword. When I have just started learning JavaScript, I used this method all the time, because it is the easiest one to memorize.

    function calc(a,b,c) {
        return a * b / c;

    Note: function declaration does not require a trailing semicolon at the end.

    Using a function declaration, we have just created exactly the same object of type Function that we did in the first example where a function constructor was used. The two functions are absolutely the same by name and in terms of what they do.

  • Function Expression is literally an expression such as function(){ } that will create a function within the context of the current JavaScript statement itself. It requires no name.

    It is often used within a single statement together in combination with a variable name or passed in as a parameter to an event (so that this function can fire whenever that event occurs in the future.) Let’s take a look at following basic examples which will help us understand how it works:

    At the bare minimum, a function expression may look like this:

    function(a,b) { return a + b };

    As you can see this is truly an anonymous function: it has no name. Entering this line into your JavaScript program as a single statement will have no effect on your program whatsoever, other than the function will be created somewhere in computer memory.

    This anonymous function, like the two before it, accepts two parameters (which become its arguments a and b within the function body,) calculates the value and returns it as the sum of the two numbers.

jQuery Tutorials