Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should closures be formatted?

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
);
like image 242
zzzzBov Avatar asked Aug 02 '11 20:08

zzzzBov


People also ask

How do you write closure?

To establish a sense of closure, you might do one or more of the following: Conclude by linking the last paragraph to the first, perhaps by reiterating a word or phrase you used at the beginning. Conclude with a sentence composed mainly of one-syllable words.

What are closures with example?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

How do you use closures?

To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function. The inner function will have access to the variables in the outer function scope, even after the outer function has returned.


1 Answers

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.

like image 107
Nobody Avatar answered Oct 10 '22 19:10

Nobody