tags:

views:

66

answers:

2
var a  = function(){
            return 'test';
         }();
console.log(a);

Answer in First Case : test

var a = (function(){
           return 'test';
        })();
console.log(a);

Answer in Second Case : test

I am using the the first approach to create self-executing functions. However, I have seen the second approach as well. Is there any difference in the two approaches ? The result is obviously the same.

+1  A: 

Yes, the first one sets the variable a as an anonymous variable, while the second one sets the variable a to the result of the function.

Edit: I read the first code wrong. The answer is no.

William
what do you mean by "a as an anonymous variable" ? how is a variable anonymous ??
Rajat
I didn't see the () on line three of the first snippet of code. They're both the same.
William
+6  A: 

The first syntax is only valid if you assign the result of the function execution to a variable, If you just want to execute the function, this form would be a syntax error:

function(){
   return 'test';
}();

The other form is still valid, though:

(function(){
    return 'test';
 })();

Therefore the second version is more flexible and can be used more consistently.

(The first form is not valid syntax to avoid ambiguities in the Javascript grammar.)

sth