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 ()()?

1
  • 2
    Not really a duplicate of either. This question acknowledges the scope issue with the function, but questions the purpose of the second set of parens. Commented Aug 19, 2012 at 18:46

3 Answers 3

5

That makes it a self-invoking anonymous function.

(function() { /* function body */ }) /* <-- end of function definition */ (); // <-- invoke that function immediately 
Sign up to request clarification or add additional context in comments.

2 Comments

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
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: 2007-2010.lovemikeg.com/2008/08/17/…
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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.