Immediate function invocation syntax Immediate function invocation syntax javascript javascript

Immediate function invocation syntax


From Douglass Crockford's style convention guide: (search for "invoked immediately")

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.

updated reference, old PPT no longer exists


Immediately Called Anonymous Functions get wrapped it in parens because:

  1. They are function expressions and leaving parens out would cause it to be interpreted as a function declaration which is a syntax error.

  2. Function expressions cannot start with the word function.

  3. When assigning the function expression to a variable, the function itself is not returned, the return value of the function is returned, hence the parens evaluate what's inside them and produce a value. when the function is executed, and the trailing parens ..}() cause the function to execute immediately.


Or, use:

void function () {...} ()