57

I often see the following code:

(function () {
  // init part
})();

but I never could get my head around how it works. I find the last brackets especially confusing. Could someone explain how it works in terms of Execution Contexts (EC) and Variable Objects (VO)?

Luke
  • 18,811
  • 16
  • 99
  • 115
Alex Djioev
  • 781
  • 1
  • 6
  • 6
  • 2
    are you interested in a "formal explanation", in terms of the ECMA-262 spec? – Christian C. Salvadó Nov 18 '10 at 06:35
  • 1
    Read about the [purpose of this construct](http://stackoverflow.com/q/592396/1048572). Have a look at a non-technical [explanation](http://stackoverflow.com/q/8228281/1048572), also [here](http://stackoverflow.com/a/441498/1048572). For the syntax, see [why the parenthesis are necessary](http://stackoverflow.com/q/1634268/1048572) and [where they should go](http://stackoverflow.com/q/3384504/1048572). – Bergi Jul 16 '14 at 22:36

7 Answers7

81

The way I usually explain this to people is to show how it's similar to other JavaScript patterns.

First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):

function foo() {/*code*/}

and

var foo = function() {/*code*/};

Even if this construction looks strange, you probably use it all the time when attaching events:

window.onload=function(){/*code*/};

You should notice that the second form is not much different from a regular variable declaration:

var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};

But in JavaScript, you always have the choice between using a value directly or through a variable. If bar is 5, then the next two statements are equivalent:

var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100;   // don't use 'bar'

Well, if you can use 5 on its own, why can't you use function() {\*code*\} on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:

var foo = function() {/*code*/}; // use 'foo'
foo();                           

(function(){/*code*/})();        // don't use 'foo' 

The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.

In other words, the following three statements are valid:

5;                        // pointless and stupid
'some string';            // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful

[EDIT in 2020]

The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:

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

But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.

( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();

Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:

() => { return 5; };       // With a function body
() => { console.log(5); };

() => 5;                   // Or with a single expression
() => console.log(5);

Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:

() => 5();              // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!
Andrew
  • 14,204
  • 15
  • 60
  • 104
  • 2
    "The way I usually explain this to people is to show how it's similar to other JavaScript patterns." It was incredibly helpful, so thank you for taking your time and doing that :) – NessDan Jul 12 '12 at 18:23
  • 1
    I think you typed (function(){/*code*/}()); you meant to type (function(){/*code*/})();. Correct? – RayLoveless Dec 11 '12 at 04:57
  • No, but it doesn't matter. Douglas Crockford recommends the form I used, while lots of people recommend yours. See http://stackoverflow.com/questions/3783007/is-there-a-difference-between-function-and-function. As it happens, the reason for parens is you're trying to avoid starting the statement with `function` (so you could just as easily do `!function(){/*code*/}()` or `-function(){/*code*/}()`. I don't like everything Crockford recommends, but I think his rigorous consistency is better than the alternative of everyone-do-what-you-want, and his linting tool (JSLint) requires it. – Andrew Dec 11 '12 at 11:38
  • Very good explanation. You definitely should write a book e.g. "Pointless and stupid vs Wonderfully powerful" :) – Sergey Berezovskiy Jan 17 '13 at 10:03
  • I disagree that the best way to define an event handler is to provide code describing what you want to happen. Why not encapsulate that in a function and then just name the function as handling the event? I will admit this inline (imho indefensible) syntax is the norm in js. pity on anyone who follows behind... – greg Apr 07 '14 at 22:04
  • I never said it was the best way. My point is that most intermediate JS devs are already very familiar with anonymous functions, even if they don't realise it, and that just running with that idea a bit further makes this pattern of self-executing functions less 'magic'. – Andrew Apr 08 '14 at 03:00
  • 2
    @RayLoveless this does not appear to be the case for fat arrow functions (() => {console.log('<---------------> HERE I AM! <--------------->')}()) fails to run while (function () {console.log('<---------------> HERE I AM! <--------------->')})() works just fine its a very old comment, but still fun to stay on top of these changes. Thank you for your answer, btw. – zentechinc Apr 06 '20 at 02:03
  • 1
    @zentechinc, actually, this is an excellent point and shows how my comment on parens placement is idiomatically incorrect. That wasn't apparent in 2010. I will update my answer. – Andrew Apr 07 '20 at 07:45
51

That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.

Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.

A demonstration:

var x = 1; // global VO
(function(){        
    var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO

The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).

Community
  • 1
  • 1
ken
  • 3,650
  • 1
  • 30
  • 43
  • 7
    Now if you explained what an EC and VO were for developers who don't understand then I would have given you an up-vote, but instead of a full answer, its one I may have to Google acronyms for. – Mark Broadhurst May 29 '13 at 12:07
  • 14
    I didn't define EC and VO because the original question contained definitions for these, so if you read the question then you should already know what they mean ;) Also, these 2 pages might help you understand EC/VO's (variables) better: 1. http://jibbering.com/faq/ 2. http://jibbering.com/faq/notes/closures/ – ken May 29 '13 at 15:16
26

The code creates an anonymous function, and then immediately runs it. Similar to:

var temp = function() {
  // init part
}
temp();

The purpose of this construction is to create a scope for the code inside the function. You can declare varaibles and functions inside the scope, and those will be local to that scope. That way they don't clutter up the global scope, which minimizes the risk for conflicts with other scripts.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Respectfully, for those of you who keep upvoting this answer, the given solution does not answer any of the questions the OP asked *at all*. He asks about the last set of brackets [sic] and how the given code relates to EC's and VO's... what was provided by Guffa looks like the run-of-the-mill anonymous function answer which doesn't address the specific points the OP brings up. – ken Nov 18 '10 at 18:47
  • 3
    @ken: People seem to like how I explain what the code does, and why it's used. Just because I don't use the exact terms that you do, doesn't make it wrong. – Guffa Nov 18 '10 at 21:38
  • I never said it was /wrong/, I was just pointing out that your copy/paste answer doesn't take into account what the OP asked, that's all. – ken Nov 18 '10 at 22:00
  • Stupid Question, but what does "init part" mean? The Term "Init" confuses me – PulledBull Aug 25 '16 at 22:58
  • @PulledBull: Init stands for initialisation / initialization. In this case it just means that the code runs when the page is parsed. As that happens first, it's a good place to initialise things. – Guffa Aug 27 '16 at 12:29
  • @Guffa Thank you, but what does it mean when you use it as a mtehod ie: foo.init ? – PulledBull Aug 28 '16 at 18:49
14

I can't believe no-one has answered the ops question!

The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8

(function(x,y){
    //code here
})(5,8)

This may seem not so useful, but it has its place. The most common one I have seen is

(function($){
    //code here
})(jQuery)

which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

SEoF
  • 1,092
  • 14
  • 26
  • 1
    This can also improve performance by shortening the [scope chain](http://jibbering.com/faq/notes/closures/) for that particular variable. – ken Apr 03 '14 at 19:19
7

Self invoking anonymous function (SIAF)

Self-invoking functions runs instantly, even if DOM isn't completely ready.

jQuery document.ready vs self calling anonymous function

Community
  • 1
  • 1
Alvaro
  • 71
  • 1
  • 1
2

In simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.

i.e.

(function(a,b){
//Do your code here
})(1,2);

It same like as

var test = function(x,y) {
  // Do your code here
}
test(1,2);
Manoj Saini
  • 339
  • 2
  • 8
1

Its is called immediatly invoking function expression (IIFE). Mainly associated with the JavaScript closure concept. Main use is to run the function before the global variable changed, so that the expected behaviour of code can be retained.

  • And here's a link: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression – Luke Oct 01 '15 at 14:20