views:

46

answers:

3

What is difference between following code?

Code 1:

var f = function() {

  // function body code
  // ...
  // ...

}();

Code 2:

var f = (function(){

  // function body code
  // ...
  // ...

})();

Which one is better to use?

A: 

They're exactly equivalent given the syntax of the language.

Ignacio Vazquez-Abrams
True. It might be worth it to note that both snippits are setting 'f' to the result of a self-executing anonymous function.
dana
+2  A: 

They are equivalent. The second one might be more clear, though.

Chetan
A: 

Since it would be invalid syntax without the assignment, as in

function() {
    // ...
}();

it may be clearer to always wrap anonymous functions in parentheses.

jleedev