515

In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...
Ej.
  • 5,429
  • 3
  • 18
  • 15
  • 4
    Also have a look at a ([technical](http://stackoverflow.com/q/4212149/1048572)) [explanation](http://stackoverflow.com/q/8228281/1048572) and [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:39
  • 2
    See also [What is the purpose of wrapping whole Javascript files in anonymous functions?](http://stackoverflow.com/q/2421911/1048572) – Bergi Jul 29 '14 at 23:22
  • Why does it have the last two parenthesis, just before the semicolon? – johnny Dec 15 '14 at 17:35
  • 3
    @johnny the part before those last two parenthesis declare an (anonymous) function. Those two parenthesis call the function. – Ej. Dec 16 '14 at 18:16
  • 10
    "Immediately Invoked Function Expression" or IIFE is a [better name](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) for this. – Flimm Jul 08 '15 at 16:05
  • Here's [a helpful article](http://markdalgleish.com/2011/03/self-executing-anonymous-functions/) on the topic. Credit to Parth for finding it. – faintsignal Oct 26 '17 at 21:19
  • It seems like the community has settled on the name Immediately Invoked Function Expression (IIFE). See [IIFE on MDN](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) or [the article on Wikipedia](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression) – Flimm Oct 13 '20 at 12:15
  • You could also use a simple block statement `{ }` with `"use strict";` directive and when declaring variables and function references use the `let` keyword instead of `var`. – caiohamamura May 11 '21 at 10:48

21 Answers21

490

It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.

For example, as mentioned in a comment by Alexander:

(function() {
  var foo = 3;
  console.log(foo);
})();

console.log(foo);

This will first log 3 and then throw an error on the next console.log because foo is not defined.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Ken Browning
  • 28,693
  • 6
  • 56
  • 68
  • 8
    And also for the benefit of many people out there including a whole bunch of Netflix Engineers: IT'S JUST A FUNCTION. It is not in and of itself representative of a closure. Sometimes auto-invokers are used in conjunction with closure-relevant scenarios to do neat stuff, but if you don't see something holding on to a reference that would be garbage-collected and gone in a non-closure language, it has nothing to freaking do with CLOSURES. – Erik Reppen Aug 18 '12 at 00:25
  • 2
    So this mean, its mostly used with closure? – Pir Abdul Feb 13 '13 at 07:33
  • @AlexanderBird , not quite right... if you do without `var`, like this: `...function(){ foo=3;}`? It would set global variable, right? – T.Todua Nov 25 '16 at 20:41
  • 2
    @AlexanderBird but that already happens in local variables inside functions: `function(){ var foo = 3; alert(foo); }; alert(foo);` So I still don't get it – João Pimentel Ferreira Dec 03 '17 at 19:08
  • Ah, I get it, you achieve all these 3 features at-once: 1) you execute the function by only declaring it; 2) As any function the variables scope is only local; and 3) The function might be anonymous, not polluting the main scope – João Pimentel Ferreira Dec 03 '17 at 19:17
  • @T.Todua: You are correct that "var" is not necessary (and the implications). However, the point of this answer is that _because_ of "self executing functions" it is now _possible_ to have private scoping at all (by using "var") – Alexander Bird Dec 03 '17 at 22:27
  • 4
    If it is only for scoping, why not just use `{ let foo = 3 }`? – Giulio Aug 20 '20 at 06:24
  • 3
    @Giulio This answer is from 2009. Block scoping was only introduced later – yunzen Mar 01 '21 at 14:39
  • @ErikReppen Technically, a closure is created every time a function is declared, capturing/closing on their relevant scope. Even global functions - they capture the global scope. – Slavi May 19 '22 at 09:20
135

Simplistic. So very normal looking, its almost comforting:

var userName = "Sean";

console.log(name());

function name() {
  return userName;
}

However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?

Wait... what?

I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.

So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.

One problem: it has a function in it called 'name' same as my function.

This is what's called a collision. We've got two functions declared in the same scope with the same name. We want to avoid this.

So we need to scope our code somehow.

The only way to scope code in javascript is to wrap it in a function:

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter library's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.

We have a function in a function... which is weird to look at, but totally legal.

Only one problem. Our code doesn't work. Our userName variable is never echoed into the console!

We can solve this issue by adding a call to our function after our existing code block...

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

main();

Or before!

main();

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.

We need MORE scoping. And some way to automatically execute our main() function.

Now we come to auto-execution functions (or self-executing, self-running, whatever).

((){})();

The syntax is awkward as sin. However, it works.

When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.

So lets look at our code again, with some self-executing syntax:

(function main() {
  var userName = "Sean";
                
    console.log(name());
                
    function name() {
      return userName;
    }
  }
)();

So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar.

After many years of professional development, I strongly urge you to name every function you write for debugging purposes.

When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!

starball
  • 20,030
  • 7
  • 43
  • 238
Sean Holden
  • 1,359
  • 1
  • 8
  • 3
  • 4
    Thank you:) I was searching the internet all the way around trying to understand the advantages of IIFE in relation to normal functions in terms of variable privacy and your answer is simply the best. Everybody says that one of the best advantages is that the variables and functions inside IIFE are 'finally' private when a normal function just gives you exactly the same thing. Finally I think I got it through your explanation process. IIFE is just a function after all but now I understand why to use it.Thank you again! – viery365 Sep 20 '16 at 10:38
  • 2
    Thanks for taking the time to explain this so well. – MSC Sep 30 '16 at 18:27
  • Nice answer. I have a question on your last point, though - When you recommend that all functions be named, are you saying there's a way to do that with self-executing functions, or suggesting that everyone name the function then call it? EDIT Oh, I see. This one is already named. Duh. Might want to point out that you're justifying your use of a named self-executing function. – FireSBurnsmuP Apr 06 '17 at 16:50
  • 1
    Well my friend, this is THE answer I was looking for `:)` – João Pimentel Ferreira Dec 03 '17 at 19:13
  • 3
    I always love 2 types of answers; (1.) short, crisp and to the point. (2.) A story like explanation that sits inside your brain forever. Yours fall under (2.) – Vibhor Dube Jun 18 '20 at 13:11
  • " I strongly urge you to name every function you write for debugging purposes." if we console.log(main), it's undefined. how does the name 'main' help with debugging? – Angela P Aug 17 '21 at 05:01
  • 6 years later, this has helped me. Thank you – Jon Aug 30 '21 at 02:16
33

Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

I am a great fan :) of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It’s good for encapsulation.
  • It’s also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)

More here.

John
  • 15,418
  • 12
  • 44
  • 65
M A Hossain Tonu
  • 1,437
  • 15
  • 14
  • 44
    Point 1. How? Point 2. That's from a completely different best-practice. Point 3. What function doesn't? 4,5,6,7. Relevance? 8. Well, 1/8 ain't bad I guess. – Erik Reppen Aug 18 '12 at 00:19
  • 3
    Seven years late but, for point 1. it doesn't reduce code at all, in fact it adds a minimum of two lines of code in creating the function. – ICW Mar 03 '17 at 15:52
  • 2
    only point here is "It provides a closure which prevents naming conflicts", every other point is rewording of this or false. maybe you can simplify your answer? – pcarvalho Dec 18 '18 at 19:37
20

Namespacing. JavaScript's scopes are function-level.

Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 10
    downvotes are still coming in because I used *namespacing* instad of *scoping*; this is a matter of definition - see eg [Wikipedia](http://en.wikipedia.org/wiki/Namespace): *A namespace in computer science (sometimes also called a name scope), is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names).* and *A namespace identifier may provide context (Scope in computer science) to a name, and the terms are sometimes used interchangeably.* – Christoph Oct 01 '14 at 15:44
  • 5
    Javascript's function-level scopes provide the space that variable names live in, a *namespace*; that it is an anonymous one not associated with a namespace identifier is irrelevant... – Christoph Oct 01 '14 at 15:51
  • I think down votes are coming because your comment is not really helpfull for beginner. – Marius Jul 09 '23 at 02:23
14

I can't believe none of the answers mention implied globals.

The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/

Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.

The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)

As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.

Cristian Cavalli
  • 2,619
  • 1
  • 13
  • 11
David W. Keith
  • 2,246
  • 17
  • 20
  • 8
    Strict mode protects against implied globals. That in conjunction with an auto-invoker would have you covered. I never understood the hooplah over private properties. Declare vars inside of a func constructor. Done. If the thought of forgetting to use the 'new' keyword keeps you up at night, write a factory function. Done again. – Erik Reppen Aug 18 '12 at 00:04
12

I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

  1. Better namespace management (Avoiding Namespace Pollution -> JS Module)
  2. Closures (Simulating Private Class Members, as known from OOP)

The first one has been explained very well. For the second one, please study following example:

var MyClosureObject = (function (){
  var MyName = 'Michael Jackson RIP';
  return {
    getMyName: function () { return MyName;},
    setMyName: function (name) { MyName = name}
  }
}());

Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

Let us try some experiments:

I can get MyName using getMyName and it works:

 console.log(MyClosureObject.getMyName()); 
 // Michael Jackson RIP

The following ingenuous approach would not work:

console.log(MyClosureObject.MyName); 
// undefined

But I can set an another name and get the expected result:

MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName()); 
// George Michael RIP

Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.

  • 1
    your answer is the first time I realized that one can ( function(){ }( ) ) instead of the syntax of the question (function(){ })(); They seem to achieve the same outcome. – Angela P Aug 17 '21 at 04:48
7

Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.

Of course, on half the JS implementations out there, they will anyway.

chaos
  • 122,029
  • 33
  • 303
  • 309
7

Is there a parameter and the "Bunch of code" returns a function?

var a = function(x) { return function() { document.write(x); } }(something);

Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.

stesch
  • 7,202
  • 6
  • 47
  • 62
  • +1; I prefer an explicit `var x = something;` in the outer function over `x` as parameter, though: imo it's more readable this way... – Christoph Feb 26 '09 at 21:11
  • @Christoph: If the value of "something" changes after the function gets created, then it will use the new value and not the one at the time of its creation. – stesch Feb 26 '09 at 21:22
  • @stesch: where did you get that from? As far as I know, that's not the case; the only way to get real references in JS is by using the arguments-object, but even that doesn't work in all browsers – Christoph Feb 26 '09 at 21:50
  • @Christoph: "JavaScript: The Good Parts", Douglas Crockford (O'Reilly) – stesch Feb 27 '09 at 04:37
  • @stesch: it doesn't work the way you describe it: the new value will be used if you drop the variable `x` and depend directly on the lexical scope, ie `document.write(something)`... – Christoph Feb 27 '09 at 09:56
  • ...`x` is only necessary (either as parameter or local var) if you want to retain the value at creation even when it changes in the outermost scope – Christoph Feb 27 '09 at 09:57
5

Here's a solid example of how a self invoking anonymous function could be useful.

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

Output: 10, 10, 10, 10, 10...

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

Output: 0, 1, 2, 3, 4...

sg.cc
  • 1,726
  • 19
  • 41
3

One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.

Vibhor Dube
  • 4,173
  • 1
  • 22
  • 32
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

Short answer is : to prevent pollution of the Global (or higher) scope.

IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.

This is the other way to write IIFE expression. I personally prefer this following method:

void function() {
  console.log('boo!');
  // expected output: "boo!"
}();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.

Donovan P
  • 591
  • 5
  • 9
2

Self executing function are used to manage the scope of a Variable.

The scope of a variable is the region of your program in which it is defined.

A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.

As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.

var globalvar = "globalvar"; // this var can be accessed anywhere within the script

function scope() {
    alert(globalvar);
    var localvar = "localvar"; //can only be accessed within the function scope
}

scope(); 

So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.

Dinh Tran
  • 535
  • 4
  • 13
Adeojo Emmanuel IMM
  • 2,104
  • 1
  • 19
  • 28
2

First you must visit MDN IIFE , Now some points about this

  • this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
  • This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
SayAz
  • 751
  • 1
  • 9
  • 16
1

Self invoked function in javascript:

A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.

Kishor Vitekar
  • 537
  • 5
  • 12
1
(function(){
    var foo = {
        name: 'bob'
    };
    console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error

Actually, the above function will be treated as function expression without a name.

The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.

Newbyte
  • 2,421
  • 5
  • 22
  • 45
Madhankumar
  • 390
  • 4
  • 12
1

Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.

That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.

James Curran
  • 101,701
  • 37
  • 181
  • 258
1

Given your simple question: "In javascript, when would you want to use this:..."

I like @ken_browning and @sean_holding's answers, but here's another use-case that I don't see mentioned:

let red_tree = new Node(10);

(async function () {
    for (let i = 0; i < 1000; i++) {
        await red_tree.insert(i);
    }
})();

console.log('----->red_tree.printInOrder():', red_tree.printInOrder());

where Node.insert is some asynchronous action.

I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).

zentechinc
  • 369
  • 1
  • 5
  • 15
1

You can use this function to return values :

var Test = (function (){
        
        
        const alternative = function(){ return 'Error Get Function '},
        methods = {
            GetName: alternative,
            GetAge:alternative
            }
            
            

// If the condition is not met, the default text will be returned
// replace to  55 < 44
if( 55 > 44){



// Function one
methods.GetName = function (name) {
        
        return name;

};

// Function Two

methods.GetAge = function (age) {
        
        return age;

};





}










    return methods;
    
    
    }());
    
    
    
    
    
    
    
    // Call
   console.log( Test.GetName("Yehia") );

    console.log( Test.GetAge(66) );
borma425
  • 336
  • 5
  • 17
0

It looks like this question has been answered all ready, but I'll post my input anyway.

I know when I like to use self-executing functions.

var myObject = {
    childObject: new function(){
        // bunch of code
    },
    objVar1: <value>,
    objVar2: <value>
}

The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...

object: {
    childObject: {
        childObject: {<value>, <value>, <value>}
    }, 
    objVar1: <value>,
    objVar2: <value>
}

Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.

Garrett
  • 35
  • 2
  • 6
0

Use of this methodology is for closures. Read this link for more about closures.

srt
  • 1
  • 2
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32702874) – user16217248 Sep 18 '22 at 04:29
-4

IIRC it allows you to create private properties and methods.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198