Javascript Anonymous Closure

Trio Cheung picture Trio Cheung · Apr 16, 2013 · Viewed 10.7k times · Source

I have read a lot about closures in Javascript What are those braces for?? I read on mozilla.org which says closure should be defined as

(function(){...})();

but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, it says the closure function is

(function(){...}());

What's the difference or the latter one is wrong? what's the purpose of the last ()? Would you put some parameters inside? I am looking for a good reference.

Edit: Moreover, there is an example on Mozilla.org

var makeCounter = function() {
var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }  
};

why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.

Answer

AlanFoster picture AlanFoster · Apr 16, 2013

The syntax

(function(){...})()

is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.

Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures

For clarity :

If we have the following function

   function hello() {
      alert("Hello");
   }

We can call the function with the following

hello()

Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do

(function hello() {
   alert("Hello");
})()

Which will do the exact same as the previous example of calling hello

However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:

(function() {
    alert("Hello");
})()

Which is the notation used in your original question.