0

I found some JavaScript syntax which is unknown for me and I even don't know how it's called or what it does so I can't find any documentation.

I found it on MDC Doc Center:

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

The part I am interested in is:

var Counter = (function() {})();

What the round brackets do? How this is called and where it can be used?

Indig0
  • 5
  • 1

3 Answers3

1

(function() {})() is an immediately executed function.

This creates private scope around a block of code. This also can create a closure which can be useful to maintain state after the function ends.

You require () around function() {} because function() {}() is an illegal statement (the JS parser fails).

Also it is a habit to make sure you wrap an immediately executed function in () so that readers of your code are aware they should be interested in the return value of the function instead of the function.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • `(function {})()` is an illegal statement too. You probably meant `(function() {})()`. – Lightness Races in Orbit Apr 10 '11 at 00:52
  • `function(){}();` is perfectly valid. Many wrap the function definition itself before invoking: `(function(){})();` Crockford (and JSLint via Crockford) recommends using the former but wrapping the entirety in parens: `(function(){}());` – JAAulde Apr 10 '11 at 01:41
  • @Tomalak Geret'kal thanks, fixed that. @JAAulde `function(){}();` as not a valid expression. it throws `SyntaxError: Unexpected token (`. Of course if you prepend it with `var foo = ...` then it will work. Whether to wrap the function or the entire invoking is a matter of personal preference and coding style. – Raynos Apr 10 '11 at 13:02
0

It's the module pattern. It's usually used to create singletons. See this answer:

What is this design pattern known as in JavaScript?

Community
  • 1
  • 1
Cristian Sanchez
  • 31,171
  • 11
  • 57
  • 63
  • "used to create singletons" It's used to create a closure. Wrapping a block of code in a self executing function creates private scope and a closure for said scope. – Raynos Apr 10 '11 at 00:33
  • @Raynos: The pattern can be used to create singletons. This is addressing the OP's inquiry as to where this pattern (or "syntax") can be used. From my experience it is usually used to create singletons. – Cristian Sanchez Apr 10 '11 at 00:49
  • @CDSanchez: He's asking about the syntax, not the pattern. – Lightness Races in Orbit Apr 10 '11 at 00:51
  • @Tomalak Geret'kal: I understand that. But the OP is ignorant to the fact that this syntax is in fact established as the module pattern. He is not going to ask about the pattern when he doesn't even know it's a pattern in the first place. I'm answering this from the perspective of where this question will eventually lead: i.e what is this called and how can I use it? It is the module pattern and it can be used to create singletons (among other things). There are countless resources on SO and the web regarding the internals of the module pattern. – Cristian Sanchez Apr 10 '11 at 01:02
  • @CDSanchez: Basic function call syntax has nothing to do with the module pattern. Read where he says "The part I am interested in is...". It's very clear. – Lightness Races in Orbit Apr 10 '11 at 01:06
  • @Tomalak Geret'kal: Touché. I overlooked that part. I knew he didn't understand the self invocation but I assumed that was the most uninteresting part considering the end result. – Cristian Sanchez Apr 10 '11 at 01:49
  • @CDSanchez yes you are correct, but it would have better to phrase your answer as "this is the syntax your asking about ... and this is the particular pattern your creating with that syntax in your example". I will again place _emphasis_ that creating modules is only a small sub-pattern of the general pattern that is creating _new scope and closures_ using that syntax. – Raynos Apr 10 '11 at 13:05
0

Consider when you have a function called a:

function a() {
   alert("hi");
}

You call it like this:

a();

In (function() {})() you're just skipping the part where you defined the function before-hand. In one fell swoop, you've defined an unnamed function and called it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055