Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 417
Rajat Avatar asked Dec 17 '22 03:12

Rajat


1 Answers

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

like image 102
sth Avatar answered Apr 20 '23 04:04

sth