I've always thought of parenthesis as mainly being a way to organize code and make sure order of operations went in the right order. However, I've recently encountered some code that makes me wonder if they're doing something else behind the scenes.
I had assumed that the parenthesis wrapping the function definition in this code block were there for readability:
(function foo(){alert('hello world!')})();
However, if I remove them, I get an error.
function foo(){alert('hello world!')}(); //SyntaxError: Unexpected token )
This sort of makes sense because I can imagine that the }
at the end of the function ends the statement and the ()
is called independent of the function (which throws the same error), while wrapping the function in parenthesis returns the function, which can then be called.
However, the following code works:
(function foo(){alert('hello world!')}())
This is the same as the second code chunk, except the entire thing is wrapped in parenthesis. I have no idea why this doesn't throw the same error as function foo(){alert('hello world!')}()
, and was hoping someone could cast some light on the issue.