Revealing Module Pattern Function Initialization Style

design-patterns, javascript

Solution

In that specific case, there's no effective difference.

Some people like the outer `(...)` because it gives them a visual hint near the `=` operator that the function is being invoked.

But the assignment operator causes the `function` to be evaluated as the expression that is the right hand operand of the assignment operator, and as such it can be invoked without any further need to coerce it out of a function declaration.

Without the assignment, there needs to be some syntax involved that lets the interpreter know that the `function` keyword is being used as an anonymous function expression.

For example...

(function() {
   // code
})();

Here the parentheses resolved the ambiguity of `function` so that it's treated as the single expression inside the `(...)` group.

The grouping operator is just one way of forcing a `function` to be evaluated as an expression. Most JavaScript operators can be used for this purpose. Unary operators are probably safest, for example...

!function() {
   // code
}();

...or...

void function() {
   // code
}();

In both cases, the `function` is seen as the single operand to the respective operator.

Problem

I was wondering, what is the significance of the additional parenthesis when initializing an object. For example: ``` var foo = function(){ ... }(); ``` versus ``` var foo = (function(){ ... }()); ``` I assume something related to scope but I was wondering if someone can be more precise about the specific differences since they both seem to initialize an object based on what each anonymous function returns.

Original source