Gary Willoughby Gary Willoughby - 1 year ago 72
Javascript Question

Why is this function wrapped in parentheses, followed by parentheses?

I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?

(function() {



Why is this written like this? Why not just use
by itself and not in a function?

EDIT: i know this is defining an anonymous function and then calling it, but why?

Answer Source

This defines a function closure

This is used to create a function closure with private functionality and variables that aren't globally visible.

Consider the following code:

    var test = true;

variable test is not visible anywhere else but within the function closure where it's defined.

What is a closure anyway?

Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.

Check this code and read comments along with it:

// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
    // no functions whatsoever

    // closure part
        // private variables and functions
        var closureVar = 222;
        var closureFunc = function(value){
            // call public func
            // alert private variable

        // add function to public object that accesses private functionality
        pubObj.alertValues = closureFunc;

        // mind the missing "var" which makes it a public variable
        anotherPublic = 333;


// alert 111 & alert 222

// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"

Here's a JSFiddle running code that displays data as indicated by comments in the upper code.

What it actually does?

As you already know this

  1. creates a function:

    function() { ... }
  2. and immediately executes it:

  3. this function may or may not accept additional parameters.

jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:

(function(paramName){ ... })(jQuery);

But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download