Let's start with a simple concept.
1 + 1
=> 2
Adding parens clarifies order of operations.
1 + 2 * 2
=> 5
(1 + 2) * 2
=> 6
Using parens when it's not necessary is harmless.
(1 + 1)
=> 2
Javascript is syntax heavy so it can be difficult to know which parts are required vs. optional.
What happens when you want to create an free standing anonymous function?
function(){ }
=> SyntaxError: Unexpected token (
To prevent syntax error, wrap the function with parens
( function(){ } )
=> function (){ }
If you want to define it, then run it, you'll need to wrap the definition in parens to separate definition from execution.
(function(){})()
=> undefined
The function body does nothing. So, here we expect the function to simple return undefined
It's a syntax error if you try to define and invoke the anonymous founction.
function(){}()
=> SyntaxError: Unexpected token (
var a = function(){}
=> function (){}
Calling the variable will return the function itself, which is different than invoking the function.
a
=> function (){}
Add the parens if you want the function to execute.
a()
=> undefined
undefinded
is the function body.
Again, wrapping the whole assignment in parens does nothing.
(a = function(){})
=> function (){}
The a =
is unecessary if you're calling it immediately
But, you will need to wrap the declaration in parens to define it and run it at the same time.
(a = function(){})()
=> undefined
Since we are defining then immediately calling the function assigning to a
isn't neccssary.
Which was the moment I realized the following line was productive!
(function(){})()
=> undefined