1

Possible Duplicate:
What is the purpose of a self executing function in javascript?
Explain JavaScript's encapsulated anonymous function syntax

for instance:

(function($) {
document.getElementById("foo").innerHTML = 'bar';
})();

I understand that we want to create our own scope to prevent variable collision but why does javascript need to have ()()?

Community
  • 1
  • 1
Sean
  • 779
  • 6
  • 18

3 Answers3

5

That makes it a self-invoking anonymous function.

(function() { 
    /* function body */ 
}) /* <-- end of function definition */ (); // <-- invoke that function immediately
Major Productions
  • 5,914
  • 13
  • 70
  • 149
  • is it just a standard javascript syntax to be able to wrap parenthesis in a function as well as invoke that function? I think the real question I am trying to ask is what the parenthesis is in javascript and what it can do – Sean Aug 19 '12 at 19:19
  • The first pair of parenthesis tell JavaScript to treat the function definition as an expression. The second pair tell it to invoke it. That second pair is no different than any other function invocation, like `someFunction();` It only looks weird because the function itself is anonymous/isn't named. More info: http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/ – Major Productions Aug 19 '12 at 22:35
5

That doesn't have ()(), it has (function(){})().

The function syntax is function(){} and the function call operator is (). The parentheses that wrap the function are not technically special and you could instead replace them with !:

!function(){}()

Doing this wouldn't work:

function(){}()

Because this in a statement context, the function starts a function declaration rather than expression. The syntax then fails because a function declaration must have a name.

If we have !function(){} (or (function(){}), then it couldn't be a statement because ! (or () already expects an expression, so it will be treated as an expression.

So you could do this without any extra:

var a = function() {
        return false;
}();

Because var a = is already expecting an expression, function cannot possibly be the start of a function declaration.

An easy way to litmus test whether your function will be seen as an expression or declaration is to ask yourself, could I use var x here?

For instance:

var x; //all is fine, so if I said function here, it would be a start of a function declaration

(var x) //Gives an error, so replacing var x with a function would be a function expression

var myVar = var x; //Gives an error, so replacing var x with a function would be a function expression

And so on

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

The first results in the function, in the same way that (2) results in 2. The second calls it.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358