Steve Hanov
Steve Hanov

Reputation: 11584

Why do many javascript libraries begin with "(function () {"?

Why do many javascript libraries look like this:

(function () { 
    /* code goes here */ 
})();

It appears to define an unnamed function which is immediately called. Why go through this effort?

Upvotes: 13

Views: 617

Answers (5)

Praveen Prasad
Praveen Prasad

Reputation: 32117

var $={} // a name space is defined 

(function($) {
        $.a_variable="some vale"
        var b_variable = "some more value";
})($);

$.a_variable // acess it like this.

now any thing inside anonymous function has scope equal to that function only also we can create objects that may act as properties to our name space.

Upvotes: 0

kemiller2002
kemiller2002

Reputation: 115508

If forces scope declaration. By putting it in a function you are making sure that the variables you create and call aren't being re-declared or you aren't accidentally calling variables which are declared elsewhere.

so.....

var variable = 5; // this is accessible to everything in the page where:

function ()
{
   var variable = 7 // this is only available to code inside the function.
}

Here is a link to Douglas Crockford's site talking about scope in Javascript:

http://javascript.crockford.com/code.html

to follow up on the comment below:

JavaScript's scope is a little "broken":

function ()
{
   var x = 3;  // accessible in the entire function.
   //for scope reasons, it's better to put var y = 8 here.....
   if(x != 4)
   {
       var y = 8; //still accessible in the entire function. 
                  //In other languages this wouldn't be accessible outside 
                  //of the if statement, but in JavaScript it is.  

   }

}

Upvotes: 7

Sean Devlin
Sean Devlin

Reputation: 1692

JavaScript doesn't have block scoping, only function scoping. By creating and immediately invoking an anonymous function, we can guarantee that its local variables won't step all over the global namespace. It's basically a way to limit conflicts with other libraries that may be in play.

Upvotes: 1

vava
vava

Reputation: 25381

This is standard way to do namespacing in JavaScript. If you just declare

var my_cool_variable = 5;

it will be global and might conflict with other libraries, that use the same variable.

However, if you do

(function() {
    var my_cool_variable = 5;
})();

it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var in front of variable, that way it will be global but now you have a choice.

Upvotes: 18

John Parker
John Parker

Reputation: 54445

At a simple level it keeps the global namespace clean(er).

i.e.: It's effectively adding a layer of wrapping around the functions and variables within the library hence ensuring there aren't any namespace clashes with other functions that may be in use from other libraries, etc.

Upvotes: 2

Related Questions