2

What means this construction in JavaScript :

   (function (){
      alert("bla");
   })();

?

piokuc
  • 25,594
  • 11
  • 72
  • 102
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236
  • 4
    [Immediately Invoked Function Expression](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) – Rikonator Apr 07 '13 at 07:50
  • Well.. at least I know I was right in my guess.. should have posted that. – Daedalus Apr 07 '13 at 07:50
  • or "[What is the purpose of a self executing function in javascript?](http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript)" – dequis Apr 07 '13 at 07:54

5 Answers5

6

The acronym for this pattern is an "IIFE" or an Immediately Invoked Function Expression.

It basically creates an anonymous function function(){}

function(){alert("bla");}

then wraps it as an expression ()

(function(){alert("bla");})

then executes it ()

(function(){alert("bla");})()

Note that at this point, you can pass arguments in as well like this:

(function(text){alert(text);})("bla")
Travis J
  • 81,153
  • 41
  • 202
  • 273
2

It's an anonymous block - declare an anonymous function then execute it immediately, meaning that any variables declared in the block are not seen outside it. In this case with the alert() it makes no difference.

Adam
  • 35,919
  • 9
  • 100
  • 137
2

You define a an anonymous function, which you immediately call.

See also What is the purpose of a self executing function in javascript? for an explanation of the purpose of the construct, which is, in short, to keep names private to the code wrapped in the anonymous function.

Community
  • 1
  • 1
piokuc
  • 25,594
  • 11
  • 72
  • 102
2

It is an anonymous function which will be excecuted one time automatically after loading

JS function definition : meaning of the last parentheses

Community
  • 1
  • 1
sdespont
  • 13,915
  • 9
  • 56
  • 97
2

Here you define an anonymous function to be executed immediately.

The function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. It returns the value of the newly created function, so by adding parenthesis after it, you may immediately invoke it.

Christian-G
  • 2,371
  • 4
  • 27
  • 47