10

I'm reading the book secrets of the js ninja, and very often I saw code like this

(function(){
  something here;
  })();

Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • Yes the function keyword returns the anonymous function, the () at the end invokes that function. Also see [this question](http://stackoverflow.com/questions/9091289/javascript-anonymous-function-call) for the same issue. – G. Lombard Jul 13 '13 at 20:10
  • @CrazyTrain http://www.jslint.com/ – Royi Namir Jul 14 '13 at 06:45
  • @RoyiNamir: But you're the one saying that it's better. You must have some reason to believe this. I did try http://jslint.com but won't give me a reason either. –  Jul 14 '13 at 12:41
  • @CrazyTrain better via validation. ( the correct word is "referred") – Royi Namir Jul 14 '13 at 12:42
  • @RoyiNamir: Nah, the correct word is "irrelevant". jsLint imposes arbitrary restrictions without any rational reason. –  Jul 14 '13 at 14:12

5 Answers5

6

Its a self calling function, that invokes its self as the script finishes loading. You can call it without arguments, or you can add arguments to it such as window or document.

You use it in a way that jQuery use it:

(function( window, undefined ) {
    // jQuery code
})(window);

An (almost) alternative syntax to do the same thing:

! function( window, undefined ){
    // some code…
}(window);

Read more at: http://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/

bizzehdee
  • 20,289
  • 11
  • 46
  • 76
  • I'd prefer the `!` operator since it's a prefix unary operator, which means it'll never try to operate on some leading expression, like the `()` can. –  Jul 14 '13 at 12:52
5

This

(function(){
  alert('hello');
})();

although it is a function is it called automatically so you dont/can't call it manually

These can be useful for for loops like so

This will fail because i would be equal to 9 after 5 seconds

for(var i = 0; i < 10; i++) {
   window.setTimeout(function(){
      console.log(i);
   }, 5000)
}

So you could do this

for(var i = 0; i < 10; i++) {
   (function(a){
      window.setTimeout(function(){
         console.log(a);
      }, 5000)
   })(i);
}

Also good for creating a "private" scope like this

(function(){
   var test = 'hello';
   console.log( test ); // 'hello'
}());

   console.log( test ); // 'undefined'
iConnor
  • 19,997
  • 14
  • 62
  • 97
3

The last set of parentheses causes the function to execute immediately. A function is created and executed without ever assigning it anywhere. The reason one might wrap their code in a function like this is to encapsulate code. Take this for example:

var myVar = 'whatever';
function shout() { alert(myVar); }

Here, myVar and shout have just become global variables. You can open up your console and type window.myVar or window.shout and you'll be able to access and change those variables. By wrapping it in a function, those variables remain local to the outer function:

(function() {
    var myVar = 'whatever';
    function shout() { alert(myVar); }
})();

window.myVar and window.shout are undefined. The only exist inside that function.

The pattern is also used to create a closure around local variables. See JavaScript closure inside loops – simple practical example.

Community
  • 1
  • 1
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
0

Self invoking function, basically it calls itself stright away.

Used normally to pass in a variable like jQuery to insure that $ is truly the jQuery object!

(function($){
    // $ now is equal to jQuery
})(jQuery);
Zevi Sternlicht
  • 5,399
  • 19
  • 31
0

It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars and functions, they will be kept within the scope of that function() you just created.

In short, it encapsulates code.

mash
  • 14,851
  • 3
  • 30
  • 33