1

Possible Duplicates:
Why this kind of function invocation is wrong in JavaScript?
Is there any reason to wrap anonymous JavaScript functions in braces?

Is there a good explanation why I have to wrap an anonymous functions in parentheses before I can call it, like this:

(function() { alert('foo'); })();

instead of just

function() { alert('foo'); }();

?

There are other languages in which functions are just things you can pass around, like for example Clojure. In Clojure a function call looks like this: (function args), for example: (+ 1 2). You can just substitute an anonymous function anywhere you would normally use a named function: ((fn [a b] (+ a b)) 1 2). In Javascript this seems not to be the case.

Community
  • 1
  • 1
Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149
  • or even this `(function() { alert('foo'); }());` – Russ Cam Dec 20 '11 at 23:17
  • So you know, there are many ways to make it an anonymous function expression besides the parentheses. For example `+function() { alert('foo'); }();`. You may encounter a specific issue if you use parentheses. –  Dec 20 '11 at 23:39
  • The simplest way I think this could be explained (probably the worst) - as functions are objects and vice versa, so adding brackets around the function, you are making an object out of a definition. – Bakudan Dec 21 '11 at 00:44

1 Answers1

1

Because without parentheses around the function, the code is a bad function declaration and adding the () to its end is a syntax error.

With parentheses around the function, however, you get a function pointer to an anonymous function which can be executed by adding () to its end.

cHao
  • 84,970
  • 20
  • 145
  • 172
Roman
  • 10,309
  • 17
  • 66
  • 101