views:

758

answers:

1

There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction

(function () {

  // ...

})();

would instead need to be written as

(function () {

  // ...

}());

My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form?


Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression:

var someVar = (function () {

  // ...

}());

Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is not the function itself but rather the result of the function being invoked.

This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.

+11  A: 

From Douglass Crockfords own PPT on the issue: (search for "require parens")

Makes more clearly the distinction between function values and the values of functions.

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.

altCognito
I'm glad I read this. I've just finished reading Javascript: The Good Parts, and what I kept thinking was that assigning the result of calling a function is really bad syntax, because you have to look at the first and last lines to understand what is happening. He doesn't use the wrapping parens in the book, but I see exactly why he recommends them.
Skilldrick