What is the difference between these two:
(function () {
alert('something');
})(); # invocation parens after the wrapping parens
and
(function () {
alert('something');
}()); # invocation parens inside the wrapping parens
—both give me the same result: alerting "something".
There is no difference. Both will do exactly the same thing (invoke the anonymous function expression).
The parentheses around the anonymous function are simply there to ensure the function is parsed as an expression rather than a declaration (which is important because a declaration can't be invoked). You may also see other operators used to the same effect. For example:
// All three of the following have the same effect:
!function () {
alert('something');
}();
+function () {
alert('something');
}();
(function () {
alert('something');
}());
Note that if you use a static analysis tool like JSLint it may complain about the first form in your question (with the invoking parentheses outside the grouping operator). The reason for this is that some people consider the second form easier to understand.
JSLint treats the })();
invocation as "wrong". The function definition and invocation are part of a single expression. It's quite logical for that reason alone that the invocation is part of the expression itself.
In essence, that's just a matter of personal preference. Personally, I find
(function(elem)
{
})(document.getElementById('foo'));
Easier to read than
(function(elem)
{
}(document.getElementById('foo')));
but then again, any editor with syntax highlighting nullifies that argument.
Bottom line: use the one you feel most comfortable with, and let jslint nag about it, Douglas Crockford is an authority when it comes to JS, but that doesn't mean we all have to blindly copy his style/reasoning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With