Is there any reason to wrap anonymous JavaScript functions in braces?

javascript

Solution

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.)

Problem

``` 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.

Original source

Related problems