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:
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With