1

Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?

My question having these special characters, I couldn't find a good answer. (Does anyone know how to search with them?)

I've seen two patterns to immediately calling anonymous functions http://jsfiddle.net/ukqS8/1/

(function(d) {
    document.write(d*2);
})(3);

and

(function(x) {
    document.write(x*2);
}(3));

The difference being where (3) is placed: inside or outside the closing parenthesis.

I found a good explanation for the second case here:

javascript function vs. ( function() { ... } ());

which I understood as function(x) {...} creates a function object, (3) becomes its argument, and the enclosing () tells the interpreter that what's inside is a statement.

In the first case, it appears to make (function(d) {...}) a statement that somehow is also a function, and then apply (3) to this statement/function.

So, they both appear to execute the same way. Is there really a difference here? Scope (I doubt it)? Is either option preferable?

Community
  • 1
  • 1
Heitor Chang
  • 6,038
  • 2
  • 45
  • 65

2 Answers2

2

Your understanding is incorrect.

Those are both function expressions; the placement of the parentheses makes no difference here.

However, there can be a subtle difference.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

They execute exactly the same. The difference is only in syntax.

Adrian Schmidt
  • 1,886
  • 22
  • 35