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:
1 2 3 4 5 6 7 | 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.
1 2 3 4 5 6 7 8 9 | // does not work (syntax error) function(){ return 'value1'; }(); // works fine (function(){ return 'value1'; })(); |
To clarify, the former is a FunctionDeclaration (which requires an identifier), the latter is a FunctionExpression (p164, A.5).
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Thanks for the link Matt!
Thanks for clarification
I recently read about anonymous functions in Resig’s “Pro Javascript Techniques”, but haven’t thought about it.
Also matt, kudos for documentation link