What is this practice called in JavaScript?
Asked Answered
H

7

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?

Harrisonharrod answered 15/9, 2010 at 17:48 Comment(8)
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.Harrisonharrod
Yes, you're right, I noticed this too, just after I clicked the button.Fiedling
that is a totally different question about the interactions of parens with IE, not about what the above practice is calledHarrisonharrod
There's a better syntax: #939886Mcculley
@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).Anissa
@MarcelKorpel, ShaggyFrog: No, it's not a duplicate. These others are merely about syntax, not about the pattern itself.Jinajingle
@Jinajingle why did you mark this as duplicate? It appears the linked question was asked a year after mine?Harrisonharrod
@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.Jinajingle
D
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.

Donnenfeld answered 15/9, 2010 at 18:1 Comment(7)
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.Ottar
@Nick Craver: see edit. I meant an effect, but the intended effect.Donnenfeld
@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.Gobo
@Gobo - 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."Ottar
@Nick: even then it's not a closure, it's an anonymous function. The two concepts are separate though closures depend on functions.Gobo
@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).Gobo
@Gobo - 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.Ottar
O
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){.

Ottar answered 15/9, 2010 at 17:51 Comment(16)
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 jibbering.com/faq/notes/closuresMelodeemelodeon
@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)."Ottar
@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.Regazzi
@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.Ottar
@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.Regazzi
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.Gobo
@Gobo - 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?Ottar
@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.Gobo
@Gobo - 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.Ottar
@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.Gustaf
@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.Ottar
@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?Gustaf
@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…Fiedling
@Mick and Nike: …sure.” (5th ed., p. 144)Fiedling
@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.)Gustaf
@Mike: I'll look into that, thanks. David Flanagan wrote JavaScript: The Definitive GuideFiedling
M
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.

Melodeemelodeon answered 15/9, 2010 at 17:51 Comment(3)
I personally call it a self-calling-function. The moment I say that phrase most seasoned javascript developer know what I'm talking about.Gobo
I call it anonymous scoping functionMisvalue
It doesn't call itself. The function just happens to be called immediately. There is no recursion going on, no "self-executing".Anissa
A
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).

Anissa answered 27/12, 2010 at 16:0 Comment(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".Anissa
C
6

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

Cocteau answered 30/9, 2010 at 21:17 Comment(2)
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.Anissa
So it only counts as a module if it returns an object (possibly with private state hidden in local variables)? Too bad.Cocteau
J
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.

Jinajingle answered 20/7, 2014 at 19:44 Comment(0)
Z
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.

Zayin answered 28/12, 2010 at 18:30 Comment(1)
simplistic example: ((lambda () (let ((foo (lambda () (+ 1 1)))) (foo))))Zayin

© 2022 - 2024 — McMap. All rights reserved.