6

I ran a script through JSLint and it picked out a specific issue with parenthesis placement.

I had written:

(function(){})();

And it was suggested to use:

(function(){}());

I'm curious as to what bugs or issues this particular change fixes. I would assume that because JSLint picked it out as an issue, there must be an issue for someone.

Expanded forms:

(
  function (p) {
    ...code...
  }
)(param); //parameters after the parens

-vs-

(
  function (p) {
    ...code...
  }(param) //parameters within the parens
);
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 2
    http://stackoverflow.com/questions/5938802/are-function-and-function-functionally-equal-in/5938845#5938845 – SLaks Aug 02 '11 at 20:37
  • @zzzzBov Wow, you clearly didn't read anything past the first sentence of the answer that SLaks linked to. It contains an extremely detailed breakdown of the differences between the two syntaxes that answers your question exactly. – Chris Shouts Aug 02 '11 at 20:51

2 Answers2

5

The specific issue JSLint is trying to fix relates to a lack of closing ; which can cause a bug where a function is interpreted as an argument:

(function A( arg ){
    // stuff
})

(function B(){
   ...
});

Is perfectly valid, B is passed to A as arg. However, this is often not the intended case as often these are meant to be self-executing and the trailing () were forgotten. The suggested syntax removes any confusion that you may have accidentally forgotten to execute your function as intended.

For what it's worth, I pretty much always use the first syntax as well; habit.

0

According to Crockford on http://www.yuiblog.com/crockford/ (can't remember which video, but I think it's towards the beginning) it is pure styling to help make it easier to read and is not related to bugs or issues.

Edit:

I think it is in Act III: Function the Ultimate

Lance
  • 1,889
  • 14
  • 12