57

When you wrap your JavaScript code in a function like this:

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?

Rubén
  • 34,714
  • 9
  • 70
  • 166
stevebot
  • 23,275
  • 29
  • 119
  • 181
  • 1
    possibly, but I was interested in the name of the practice, not the effects and understanding of the mechanics, which I believe the other question is concerned with. – stevebot Sep 15 '10 at 21:39
  • Yes, you're right, I noticed this too, just after I clicked the button. – Marcel Korpel Sep 15 '10 at 22:19
  • 1
    that is a totally different question about the interactions of parens with IE, not about what the above practice is called – stevebot Sep 21 '10 at 14:40
  • There's a better syntax: http://stackoverflow.com/questions/939386/javascript-immediate-function-invocation-syntax – DanMan Dec 28 '10 at 18:01
  • 1
    @DanMan...it is the same exact thing. Crockford just happens to like the "calling" parenthesis on the "inside". It's just a personal preference (I actually agree with Crockford's preference on this one). – David Murdoch Dec 29 '10 at 01:46
  • @MarcelKorpel, ShaggyFrog: No, it's not a duplicate. These others are merely about syntax, not about the pattern itself. – Bergi Jul 16 '14 at 21:50
  • @Bergi why did you mark this as duplicate? It appears the linked question was asked a year after mine? – stevebot Jul 17 '14 at 18:58
  • 1
    @stevebot: It's basically the same question imo. And it features a good - better - answer with the correct (and nowadays widely adopted) term "immediately invoked function expression". This thread seems to lack such, even if you'd consider to accept DavidMurdoch's answer instead. Questions are closed as dupes based on the quality of answers, not on the time they were asked - don't feel offended, you deserve the fifty upvotes. – Bergi Jul 17 '14 at 19:03

7 Answers7

37

The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.

Matt
  • 74,352
  • 26
  • 153
  • 180
palswim
  • 11,856
  • 6
  • 53
  • 77
  • 1
    I'm not sure how you call this a side-effect...if you wanted to execute the code immediately (and *not* a closure) why wrap it in a function in the first place? It's a direct and intentional effect. – Nick Craver Sep 15 '10 at 18:02
  • 1
    @Nick Craver: see edit. I meant an effect, but the intended effect. – palswim Sep 15 '10 at 18:07
  • 7
    @Nick: a closure is a possible side effect. A function is **not** a closure. A function without a name is called an anonymous function, mistakenly called a closure by those not familiar with functional languages. In javascript things declared in braces `(..)` are expressions, so that is an anonymous function expression. All expressions return something. In the case of function expressions it returns a reference to a function. None of the things above are called closures in the traditional sense. A closure is a variable shared between functions, not the function itself. – slebetman Sep 15 '10 at 18:36
  • 1
    @slebetman - You didn't read the comments above, or my updated answer from 20 minutes ago, I clarified exactly this: "It's only a closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately." – Nick Craver Sep 15 '10 at 18:37
  • 2
    @Nick: even then it's not a closure, it's an anonymous function. The two concepts are separate though closures depend on functions. – slebetman Sep 15 '10 at 18:44
  • 1
    @Nick: to use your own phrasing to explain: `when something inside that scope is exposed to an outer scope` then that `something` is called a closure (not the scoping mechanism itself which is a function). – slebetman Sep 15 '10 at 18:45
  • 1
    @slebetman - You're right I should have added "creating" there was well (it was already in the answer, so I thought people could read this easily...). I've updated to hopefully make it crystal clear, even when taking snippets of the answer. – Nick Craver Sep 15 '10 at 18:49
20

To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.

There are some excellent answers here that explain the why a bit more: How does a javascript closure work?

It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.

The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.

Community
  • 1
  • 1
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 12
    Strictly speaking a closure is a side-effect of the function. This isn't a closure, it's a function. In fact, there probably isn't even a closure being created in this case, since the function's contents aren't accessible from outside it. See http://jibbering.com/faq/notes/closures/ – Jani Hartikainen Sep 15 '10 at 17:58
  • 2
    @Jani - That's what a closure does... it's specifically for (in this case) hiding the contents from the outside, while having them accessible to anything inside. Even the link you provided gives this *exact* definition: "The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s)." – Nick Craver Sep 15 '10 at 18:01
  • 3
    @Nick, the line you quote is referring to the way the Identifier Resolution process works, not specifically with the formation of a closure, continuing with the quote: "A *closure* is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned." So if no *inner* function is made available to the outside, a closure is *not* formed -what @Jani points out-, IMO the term *closure* is sometimes overused nowadays. – Christian C. Salvadó Sep 15 '10 at 18:08
  • 1
    @CMS - You can't tell from the example if that's the case or not though. For example what if the next line is `window.method = doSomething;`? The OP is asking a general question about the wrapper, and in my experience, *most* of the time you're exposing *something* to the outside, though I concede that's not *always* the case. I clarified a bit above that I'm answering the common case, not specifically his (partial) example. – Nick Craver Sep 15 '10 at 18:10
  • 3
    @Nick, yeah, the example is incomplete. Yes, you almost always expose something to the outside, in the case of a *function* (or an object containing a property that references to a local function) a closure is formed. Thanks for the clarification. – Christian C. Salvadó Sep 15 '10 at 18:19
  • 1
    But he's not asking about what happens to variables captured in the anonymous function (which is what closures are). He's asking about an anonymous function declared as a function expression being immediately called. You are answering the wrong question. – slebetman Sep 15 '10 at 18:29
  • 1
    @slebetman - His question **specifically** mentioned scoping problems on pages, how are you saying this isn't answering the question? It's an anonymous function, being immediately called and it's *probably* a closure (though we can't be sure without the entire code), what exactly did I leave out? – Nick Craver Sep 15 '10 at 18:31
  • 2
    @Nick: A function is **not** a closure. Don't get your terminologies mixed up. A closure is the variable shared by functions. A function can **create** a closure but it in itself is not a closure. It's like calling an oven a cake. A cake is not an oven but an oven may be used to bake a cake. – slebetman Sep 15 '10 at 18:42
  • 2
    @slebetman - I don't believe I said a function *is* a closure, you won't get any debates from me there (in fact, it's on the first line of the answer: " **creating** a closure"). I'm saying this is *probably* **creating** a closure, as in that's its main purpose (though, again, we can't tell without see the entirety of the code). I apologize if you're not reading that, I thought the clarification half an hour ago articulated this pretty clearly, I'll try to refine it to make it even clearer. – Nick Craver Sep 15 '10 at 18:44
  • 1
    @Nick: Remember if you use window or variables like document (which are evaluated as window.document), you are using javascript's global variables, and are not, in fact, using any closed variables. – Mike Axiak Sep 15 '10 at 18:58
  • 1
    @Mike - In my example in response to CMS like `window.method = doSomething;` you see from the question `doSomething` is in question...you're providing access to that scope with this reference, creating a closure, and you *are* using closed variables in there when the function's called. – Nick Craver Sep 15 '10 at 19:02
  • 2
    @Nick, In your example it is, but in my experience, most times people use this pattern, they are only accessing global variables (whether it's jquery, window, document, etc). Such pattern is thus not usually using closures, and thus we don't need to confuse people with this terminology just because it's "the hip term". Also, I think what bothers me is that while a closure could possibly be used, it's not the *essential* feature going on here. Yes, variables are used too, but we don't call this pattern a variable, do we? – Mike Axiak Sep 15 '10 at 19:30
  • 1
    @Mike and Nick: I think Mike is correct, but to throw some more dust in this discussion, I'll quote Flanagan's *Definitive Guide*: “JavaScript functions are a combination of code to be executed and the scope in which to execute them. This combination of code and scope is known as a *closure* in the computer science literature. All JavaScript functions are closures. These closures are only interesting, however, in the case discussed above: when a nested function is exported outside the scope in which it is defined. When a nested function is used in this way, it is often explicitly called a clo… – Marcel Korpel Sep 15 '10 at 22:28
  • 1
    @Mick and Nike: …sure.” (5th ed., p. 144) – Marcel Korpel Sep 15 '10 at 22:30
  • 2
    @Marcel: I'm not sure who Flanagan is, but Landin's original paper described a closure as having an environment and variables, and used the term anonymous functions to refer to the functions themselves. (The paper is easily accessible for free online.) – Mike Axiak Sep 15 '10 at 23:24
  • 1
    @Mike: I'll look into that, thanks. David Flanagan wrote [JavaScript: The Definitive Guide](http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ref=sr_1_1?ie=UTF8&s=books&qid=1284639563&sr=8-1) – Marcel Korpel Sep 16 '10 at 12:20
15

The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.

I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.

Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
12

Ben Alman presents an interesting argument on the commonly use terminology for this "pattern".

His blog post about it is here (http://benalman.com/news/2010/11/immediately-invoked-function-expression/).

If his post is too long for you here is my summary (I still recommend reading it as this summary leaves out a lot):

If you want a named function to be self executing/invoking it would should look like this:

// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
   foo();
}

If you want an anonymous function to be self executing/invoking it should look like this:

// Hello, I have no name...
//   (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
    arguments.callee();
};

If you want an anonymous function to be immediately executed/invoked it should look like this:

// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
//    even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
//    or "iffy" for short.
(function(){ /...code.../ }());

My own thoughts on the matter:

The other answers are correct; what you are asking about is commonly referred to as a "self invoking anonymous function."
However, that terminology doesn't accurately reflect what is really happening; "Immediately-Invoked Function Expression" (aka "iffy", for short) seems like a more appropriate term.


Fun facts to impress your friends:

You can create an Iffy like this, too:

!function(){
   alert("immediately invoked!");
}();

or

+function(){
   alert("immediately invoked!");
}();

or if you are really cRaZy ( example ):

!1%-+~function(){
   alert("immediately invoked!");
}();

in most browsers (if not all, I'm not sure) and the effect will be the same (facebook uses the ! version).

David Murdoch
  • 87,823
  • 39
  • 148
  • 191
  • 1
    I don't recommend using those "shortcuts" since most devs don't know about it and I'm not sure about browser compatibility. Test it cross-browser and if it works everywhere you could always do this: `!(function(){}());` so you still get to use the nifty `!` and the widely known "Immediately-Invoked Function Expression". – David Murdoch Jan 05 '11 at 20:19
6

Douglas Crockford and the YUI team call it the module pattern.

Sean McMillan
  • 10,058
  • 6
  • 55
  • 65
  • 1
    The module pattern is more specific than this. It use a "closure" as a way to provide private methods and variables to an object or function that is returned at the initial (immediate) invocation. – David Murdoch Dec 29 '10 at 01:52
  • So it only counts as a module if it returns an object (possibly with private state hidden in local variables)? Too bad. – Sean McMillan Jan 04 '11 at 19:56
4

What is this practice called?

It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).

Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.

For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.

I noticed that this fixes scoping problems for me on a lot of web pages.

Yes, the purpose of this pattern is to introduce an extra scope by executing a function.

The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.

dietbuddha
  • 8,556
  • 1
  • 30
  • 34