Wednesday, November 18, 2009

Javascript function(){}() vs (function(){})()

What’s the difference between function(){}() and (function(){})() JavaScript constructions? Both are right away executed anonymous functions. I have asked this question to myself mainly because of context where I have used them and they seemed to be equal to me:

var f1 = function(){
return 'value1';
}();

var f2 = (function(){
return 'value2';
})();

I was assigning return value from function to a variable and it worked the same good for both versions with and without extra set of parentheses. After playing a bit and investigating jQuery code it become clear to me that the difference is in a standalone execution. Function with extra set parentheses you can be executed anonymously while variant without parentheses can only be used in a right side of assignment.

// does not work (syntax error)
function(){
return 'value1';
}();

// works fine
(function(){
return 'value1';
})();

No comments: