Reputation: 34128
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.
Upvotes: 5
Views: 563
Reputation: 430
It is good practice (but not required) to wrap IIFEs (Immediately Invoked Function Expressions) in parenthesis for readability. If your function is long and the reader cannot see the end, the opening parenthesis calls the readers attention to the fact that there is something special about this function expression and forces them to look at the bottom to find out what it is.
Upvotes: 0
Reputation: 229593
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.)
Upvotes: 11
Reputation: 15583
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.
Upvotes: 1