What is this practice called in JavaScript?

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?

Answers:

Answer

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.

Answer

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

Answer

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.

Answer

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

Answer

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

Answer

Version 1:-

function mySpace()
{
    var obj = {};

    obj.name = "Deepak";
    obj.whoami = function ()
    {
        return obj.name;
    }

    window['myObject'] = obj;
}

mySpace();

myName = myObject.whoami();

console.log(myName);

Version 2:-

(function(){

    var obj = {};

    obj.name = "Deepak";
    obj.whoami = function ()
    {
        return obj.name;
    }

    window['myObject'] = obj;
})();

myName = myObject.whoami();

console.log(myName);

We are not calling any named function in Version 2 to initialise myObject but its available to global scope.

You are only linking <script src="jquery.min.js"></script> and $ object is available for use. That style is known as self invocation function.

Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.