(function(){ … })();

The very first time I read jQuery 1.3.2‘s code, the very first line surprised me :
(function(){

It didn’t take me a long time to discover that at the end of the library was the following :
})();

What are those symbols ? Is it some kind of mysterious signature of the author ? Why enclosing all the code within those “strings” ?

function(){} is the definition of an anonymous function. The surrounding parenthesis and the (); are here to call this function once.

Why creating a function to call it only once while JavaScript is a scripting language and as such, all the code in of the function could just be written outside of any function ?
The answer to this question can be found in one JavaScript weaknesses.

Each time a function or a variable is declared in the global context, the name of it is attached to the global object (the window object in a web browser). In C or Java, declaring a name in the global namespace, even if a bad practice, is not a big deal since when you declare a global variable or a function (or a class in Java) with the same name in different files, the compiler warns you and even refuses to compile. In JavaScript, if two functions with the same name are declared, the last one is the one that will be used. The former is forgotten without the least warning.

Without extra trick, in big enough applications with several JavaScript files, collisions are almost unavoidable. Obviously, this leads to weird bugs (“Dammit ! I called changeState(newState) and nothing changed !”) which take a lot of time to find and debug.

What helps avoiding global declaration is that within the scope of a function, you can declare variables and other function which are visible only inside of the function and not in the global context. So, within the scope of a function, you can use any variable and function name without risking any conflict with the global object (as long as you declare variables with var and functions with function X(){} or var X = function(){...};).

The idea of creating an anonymous function which is called only once is not very far.

No matter the version or the number of features, jQuery only uses two global variables : $ and jQuery, dramatically reducing conflicts risks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s