Explain the encapsulated anonymous function syntax Explain the encapsulated anonymous function syntax javascript javascript

Explain the encapsulated anonymous function syntax


It doesn't work because it is being parsed as a FunctionDeclaration, and the name identifier of function declarations is mandatory.

When you surround it with parentheses it is evaluated as a FunctionExpression, and function expressions can be named or not.

The grammar of a FunctionDeclaration looks like this:

function Identifier ( FormalParameterListopt ) { FunctionBody }

And FunctionExpressions:

function Identifieropt ( FormalParameterListopt ) { FunctionBody }

As you can see the Identifier (Identifieropt) token in FunctionExpression is optional, therefore we can have a function expression without a name defined:

(function () {    alert(2 + 2);}());

Or named function expression:

(function foo() {    alert(2 + 2);}());

The Parentheses (formally called the Grouping Operator) can surround only expressions, and a function expression is evaluated.

The two grammar productions can be ambiguous, and they can look exactly the same, for example:

function foo () {} // FunctionDeclaration0,function foo () {} // FunctionExpression

The parser knows if it's a FunctionDeclaration or a FunctionExpression, depending on the context where it appears.

In the above example, the second one is an expression because the Comma operator can also handle only expressions.

On the other hand, FunctionDeclarations could actually appear only in what's called "Program" code, meaning code outside in the global scope, and inside the FunctionBody of other functions.

Functions inside blocks should be avoided, because they can lead an unpredictable behavior, e.g.:

if (true) {  function foo() {    alert('true');  }} else {  function foo() {    alert('false!');  }}foo(); // true? false? why?