Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS anonymous function invocation syntax

Tags:

javascript

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

like image 527
Shlomi Avatar asked Dec 12 '22 20:12

Shlomi


2 Answers

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.

like image 180
James Allardice Avatar answered Dec 25 '22 15:12

James Allardice


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

like image 37
Elias Van Ootegem Avatar answered Dec 25 '22 15:12

Elias Van Ootegem