2

Possible Duplicates:
JavaScript: Why the anonymous function wrapper?
A Javascript function
How does the (function() {})() construct work and why do people use it?

I saw some code in javascript in following format :

(
 function()
 {
   //stmt
 }
)();

Why exactly do we use these standalone parentheses? Thank you.

Community
  • 1
  • 1
mihsathe
  • 8,904
  • 12
  • 38
  • 54

5 Answers5

4

This code creates a function expression, then calls it immediately.

It's the same as

var unnamed = function() { ... };

(unnamed) ();
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

The last two parantheses before the ; execute the anonymous function directly. The other two parantheses are optional and just some sort of convention.

This pattern is commonly used for not polluting the global namespace:

(function() {
  var a = 42;
})();

alert(a); // a is undefined

Paul Irish has a pretty good screencast about this and other javascript patterns: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

tbi
  • 441
  • 3
  • 3
1

This is the basis for what is called the Module pattern in Javascript. See these articles for more information:

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

http://yuiblog.com/blog/2007/06/12/module-pattern/

Essentially, as the articles state, this pattern is perfect for maintaining privacy and state, but also allow loose coupling and chaining of your Javascript modules.

Digbyswift
  • 10,310
  • 4
  • 38
  • 66
  • 1
    The example in the OP is not the module pattern, it is a simple anonymous function expression that is immediately executed. It would only be the module pattern if it actually created an object with methods accessible outside of the anonymous function - typically done by returning said object though there are other ways. But there are other, non-module reasons why you might wrap some code in an anonymous immediately executed function, e.g., to create some temporary working variables for a particular calculation without polluting the global namespace. – nnnnnn Jun 20 '11 at 01:08
  • I still liked the resources. They are good. – mihsathe Jul 06 '11 at 02:21
  • @nnnnnn: Agreed, it is not a pattern but a basis for a pattern. I have edited my post accordingly. Have an upvote. – Digbyswift Jul 06 '11 at 11:10
0

The standalone parentheses () means to execute the function, in this code, it's a anonymous function.

cxa
  • 4,238
  • 26
  • 40
0

Creates annonymous function and calls it, therefore avoiding pollution of the namespace and memory for functions that are called only once.

Although similar to:

var f = function () { ... };
f();

This variant avoids creating a variable f, which saves memory and avoids namespace conflicts.

carlosayam
  • 1,396
  • 1
  • 10
  • 15