Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  58] [ 1]  / answers: 1 / hits: 15349  / 14 Years ago, mon, august 2, 2010, 12:00:00

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.



The code used to wrap an anonymous function in parenthesis and then execute it,



(function () {
// code here
})();


but now it wraps the auto-executed function in parenthesis.



(function () {
// code here
}());


There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”



I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?


More From » syntax

 Answers
5

They're virtually the same.



The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.



The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.



I don't think there's a right way of doing it, since the result of the expression is the same.



> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
foo
> (function(){ return 'foo'}())
foo

[#96057] Thursday, July 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gonzaloulyssess

Total Points: 225
Total Questions: 114
Total Answers: 112

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;