2

Possible Duplicate:
Location of parenthesis for auto-executing anonymous JavaScript functions?
Is there a difference between (function() {…}()); and (function() {…})();?
Two ways of immediate call to anonymous function (function(d){ }() ); and (function(x){ } )();

Is there a difference between the given 2 ways of declaring and calling an anonymous function?

Option 1:

(function(){
    console.log('Declare and call anonymous function');
})();

Option 2:

(function(){
    console.log('Declare and call anonymous function');
}()); 

Both the functions are invoked once it is evaluated.But I couldn't understand the difference.

Community
  • 1
  • 1
Ahamed Mustafa M
  • 3,069
  • 1
  • 24
  • 34
  • Option 1 will guarantee that the function is defined and available before calling it. Perhaps it is done like that for compatibility (browsers can behave quite differently in situations of tricky function definition). – Brendan May 02 '12 at 18:50
  • Option 3: !function(){ console.log('Declare and call anonymous function'); }() – GillesC May 02 '12 at 18:51
  • See my answer on http://stackoverflow.com/a/3783287/5445 there's no *practical* difference, there's only a difference at the level of *grammar*. – Christian C. Salvadó May 02 '12 at 18:53
  • This question is simillar to [What do parentheses surrounding a JavaScript object/function/class declaration mean?](http://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-object-function-class-declaration-m) – Flavio Cysne May 02 '12 at 18:57

1 Answers1

1

No, there's no difference: the two options are syntactically different but semantically equivalent. Consider a named function:

(foo())

vs.

(foo)()

and perhaps it's clearer how they're the same thing.

jimw
  • 2,548
  • 15
  • 12
  • There can be a difference: `new (foo)()` is not equal to `new (foo())`. – Rob W May 02 '12 at 18:52
  • Ah, because of `new`s precedence the first example amounts to `(new (foo))()`? Good point, but I don't suppose it's worth adding that to my answer, as this question looks set to be deleted. – jimw May 02 '12 at 18:57