38
votes

Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?

This is something I haven't quite figured out yet, but I have been using function(){}() just because my VIM syntax highlight screws up if I add the parenthesis, although I've seen (function(){})() around many times, maybe its an IE thing?

edit:

var singleton = function() {
    // code
}();

var singleton = (function() {
    // code
})();
3
can you give a bit more context? - Jesse Pepper
Why can't VIM handle the parens? I'm surprised there are so many people using it if it can't handle that case. - recursive
Yes, Javascript syntax highlight gets disabled for the entire code block between the parenthesis. - Luca Matteis
In the example shown above, there is no difference, because the parser is expecting an expression after the =. When you are not assigning the output, you need the parens to disambiguate the function statement from a function expression. The parens put the parser into an expression context. - Sean McMillan

3 Answers

45
votes

Peter Michaux discusses the difference in An Important Pair of Parens.

Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises,

9
votes

The extra set of parentheses makes it clearer that you are constructing a function and then calling it. It's a coding style thing, not a functionality thing.

4
votes
function(){}();

doesn't work in most of browsers. You should use parenthesis around the function in order to execute it

(function(){})();

then browser will know that last parenthesis should be applied to all the expression

function(){}

UPD: If you don't use parenthesis, the brower could misunderstand you. If you just call the function and dismiss the result

function() {
    alert(1);
}();

then ff and ie will throw error