Wrapping a function between parenthesis ensures this function to be evaluated as a function expression.
That happens because the Grouping Operator (the parentheses), can only evaluate expressions.
If no parenthesis are used, it will be interpreted as a function declaration, and it will cause a syntax error, since the function name is not optional for function declarations.
(function(arg){
alert(arg); // alerts test
})("test");
In the above example, the function expression is automatically executed, passing an argument.
That pattern is heavily used by jQuery plugins, since jQuery can run in noConflict mode, the $
global variable will not be created, so the jQuery global object is passed as an argument of this anonymous function and inside of that function, you can freely refer to it as $
(the received argument).
Keep in mind that also, the function context (the this
keyword) inside self-executing function expressions invoked like the above example, will refer always to the Global object.
For a more in-depth info about the differences between function expressions and function declarations, give a look to the following resources: