Difference between (function(){})(); and function(){}(); [duplicate]


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
})();

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,


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.


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