Shlomi
Shlomi

Reputation: 3792

JS anonymous function invocation syntax

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".

Upvotes: 4

Views: 139

Answers (3)

11684
11684

Reputation: 7517

Wrapping something into parentheses (in JS) forces the interpreter to treat it as an expression.

In the first case you force the interpreter to treat the function as an expression, then the interpreter evaluates that, concludes it's a function an then looks further: (), so it invokes the function.

In the second case you force the interpreter to treat the invoking parens as an expression too, so the result of the function call would be the result of the expression, if it would return something (else it would be undefined - thanks Elias van Ootegem).

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

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

Upvotes: 3

James Allardice
James Allardice

Reputation: 166041

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.

Upvotes: 10

Related Questions