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.
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:
The other form is still valid, though:
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.)