0

Can someone explain to me what below code does, how it works and why it is used?

I don't understand why the function is within brackets or the brackets after the curly brackets.

(function () {
    //Some javascript code...
}());

Thank you.

Edit/Follow up question:

Now that I better understand what above does, what effect would this have when used with jQuery:

        $(document).ready(function () {

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

        });
PostureOfLearning
  • 3,481
  • 3
  • 27
  • 44

3 Answers3

3

That is a self-executing function. It creates an anonymous function and immediately executes it.

It can be used for many purposes, such as creating a new scope.

var x = 10
(function () {
    var x = 5
}())
alert(x) // 10
tckmn
  • 57,719
  • 27
  • 114
  • 156
3

This is a self executing anonymous function.

First is the anonymous function:

(function(){
  //Normal code goes here
})

The really interesting part is what happens when we add this right at the end:

();

Those brackets cause everything contained in the preceding parentheses to be executed immediately.

Javascript has function level scoping. All variables and functions defined within the anonymous function aren't available to the code outside of it, effectively using closure to seal itself from the outside world.

This design pattern is useful for modular Javascript.

You may read more here: What is the purpose of a self executing function in javascript?

Community
  • 1
  • 1
Strelok
  • 50,229
  • 9
  • 102
  • 115
0

@doornob is correct. However, there is a syntax error in the original post. It should look like this:

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

While this is commonly described as a "self-executing function", a more accurate term is "Immediately Invoked Function Expression." We can call that an "iffy." This is a type of closure.

This pattern is is commonly extended into something called the module pattern, which looks like this:

var myModule = (function() {

    var my = {};

    var privateFoo = 'I am foo. I am a private field!';

    my.publicMethodGetFoo = function() {
        return privateFoo;
    }

    return my;
}) ();

This is very much like a class in a traditional OOP language such as C++ or Java. The properties declared using the var keyword cannot be accessed outside of the module. Though there is no such thing as access modifiers in JavaScript, these properties are for all intents and purposes 'private'.

Note that we created an object called 'my'. This object is returned at the end of the module, which means it is exposed to the 'outside world.' Therefore it's accessible outside of the module. Any field or method that we add to 'my' will therefore be public.

Neil Girardi
  • 4,533
  • 1
  • 28
  • 45
  • Thanks Neil. You say it is syntax error, however, the code is copy/paste from a working solution. What is the difference between your version and the posted version? – PostureOfLearning Aug 27 '13 at 02:03
  • The anonymous function is typically wrapped in a pair of parenthesis, which causes JavaScript to evaluate it as an expression as opposed to an assignment: (function() {}) This is followed by a pair of parentheses, which immediately invokes the expression. In your example, the closing parenthesis is placed after the (). It's quite possible that it works fine the way you have it. To tell you truth I don't know. But I do know that the way I wrote it is the commonly used syntax. – Neil Girardi Aug 27 '13 at 02:15
  • Thanks. Feel free to comment on the edit of the post too. – PostureOfLearning Aug 27 '13 at 02:52