Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(...()) vs. (...)() in javascript closures [duplicate]

I know this is silly, but there's any difference between this:

(function() {       var foo = 'bar';   })(); 

and this?

(function() {       var foo = 'bar';   }()); 

JSLint tells us to Move the invocation into the parens that contain the function, but I see no need to.

Edit: The answers are too cool. ~function, the JSHint alternative along with jQuery's preference for (/***/)(); and Crockford's explanation! I thought I was going to just get a "they're the same thing" kind of answer.
You guys decide the best one through upvotes and I tick it.

like image 497
Camilo Martin Avatar asked Jan 08 '12 00:01

Camilo Martin


People also ask

What would happen if I remove the closure feature from JavaScript?

If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier. So, if you want a function to always have access to a private piece of state, you can use a closure.

Is closure unique to JavaScript?

Closures are a very powerful yet underused feature unique to of JavaScript (and other ECMAScript languages). They essentially provide your code with private variables that other scripts can't access.

What could be the alternative to closure?

Webpack, Babel, UglifyJS, and TypeScript are the most popular alternatives and competitors to Closure Compiler.


Video Answer


2 Answers

There's no difference. Both are valid ways to get the JavaScript parser to treat your function as an expression instead of a declaration.

Note that + and ! will also work, and are sometimes used by minifiers to save a character of size:

+function() {       var foo = 'bar';   }();  !function() {       var foo = 'bar';   }(); 

EDIT

As @copy points out, for completeness, ~ and - will also work.

-function() {       var foo = 'bar';   }();  ~function() {       var foo = 'bar';   }(); 
like image 57
Adam Rackis Avatar answered Oct 06 '22 01:10

Adam Rackis


That JSLint violation exists because Douglas Crockford says that the outside-parentheses version looks like "dog balls".

You can hear him discuss it in this video:

I think that looks goofy, 'cause what we're talking about is the whole invocation, but we got these things hanging outside of it looking sorta like ... dog balls.

He suggests that the parentheses inside help the reader understand that the entire statement is a function expression rather than a declaration.

like image 27
Rob Hruska Avatar answered Oct 06 '22 01:10

Rob Hruska