Wrapping a function between brackets ensures that the function will be evaluated as an expression of the function.
This is because Grouping Operator (parentheses) can only evaluate expressions.
If the bracket is not used, it will be interpreted as a function declaration, and this will cause a syntax error, since the function name is not optional for function declarations.
(function(arg){ alert(arg);
In the above example, a function expression is automatically executed by passing an argument.
This template is heavily used by jQuery plugins because jQuery can operate in noConflict mode, the global variable $ will not be created, therefore the global jQuery object is passed as an argument to this anonymous function and inside this function, you can freely refer to it as $ (received argument).
Keep in mind that the function context ( this ) inside self-executing function expressions called as in the above example will always refer to the Global object.
For more information on the differences between function expressions and function declarations, see the following resources:
CMS Jan 08 2018-10-10T00: 00-01
source share