What is this practice called in JavaScript?

JavascriptDesign PatternsTerminologyIife

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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){.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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).

Solution 5 - Javascript

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

Solution 6 - Javascript

> 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 https://stackoverflow.com/q/1634268/1048572 and https://stackoverflow.com/q/3384504/1048572. > 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.

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstevebotView Question on Stackoverflow
Solution 1 - JavascriptpalswimView Answer on Stackoverflow
Solution 2 - JavascriptNick CraverView Answer on Stackoverflow
Solution 3 - JavascriptJani HartikainenView Answer on Stackoverflow
Solution 4 - JavascriptDavid MurdochView Answer on Stackoverflow
Solution 5 - JavascriptSean McMillanView Answer on Stackoverflow
Solution 6 - JavascriptBergiView Answer on Stackoverflow
Solution 7 - JavascriptdietbuddhaView Answer on Stackoverflow