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

var a = function () { return 'test'; }(); console.log(a); 

The answer in the first case: test

 var a = (function () { return 'test'; })(); console.log(a); 

The answer in the second case: test

I use the first approach to create independent functions. However, I have seen a second approach. Is there a difference in the two approaches? The result is obviously the same.

+4
source share
3 answers

The first syntax is valid only if you assign the result of the function to a variable. If you just want to execute a function, this form will be a syntax error:

 function(){ return 'test'; }(); 

The rest of the form remains valid:

 (function(){ return 'test'; })(); 

Therefore, the second version is more flexible and can be used more consistently.

(The first form is not allowed by the syntax to avoid ambiguities in Javascript grammar .)

+11
source

Yes, the first sets the variable a as an anonymous variable, and the second sets the variable a to the result of the function.

Edit: I read the first code incorrectly. The answer is no.

+1
source

Good practice (but not mandatory) for wrapping IIFE (fictitious function expressions) in brackets for readability. If your function is long and the reader does not see the end, the opening bracket attracts the attention of readers that there is something special in this function expression and makes them look to the bottom to find out what it is.

0
source

Source: https://habr.com/ru/post/1299406/


All Articles