This question already has an answer here:
Sometimes I see this:
(function() {
alert("hi");
})();
And sometimes I see this:
(function() {
alert("hi");
}());
Note the placement of the closing paren for the function object.
What is the difference? I can't figure it out. Is either preferable for any reason?
Edit:
Also, this does not work:
function() {
alert("hi");
}();
Which seems weird, since it is valid if wrapped in parentheses, as in example 2. I don't understand why wrapping it in parentheses changes anything in that respect.
100% no difference between #1 and #2, at all.
#3 is tricky.
You declare functions like this:
function funcName () { }
JS will actually go through your code and pick out all of the function declarations which are written like that (within your current scope), before it even looks at the rest of the code in that scope.
So for instance, if you write:
It works, because JS entered that scope, picked up the function declaration, and then looked at the rest of your scope (which is why it doesn't throw an
undefined is not a function
reference-error at you).So writing:
JS will now see that as
Of course, JS will never make it as far as the
()
because a declaration with no name is a big deal.Which is where the parens come in:
(/* evaluate what's in here */);
The subtle difference between #1 and #2 is this (real-world difference -- 0%):
...except that I cheated. In JS, the entire chain of the expression is evaluated before the left-hand is assigned...