(... ()) vs. (...) () in javascript closure

I know this is stupid, but there is a difference between this:

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

and this?

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

JSLint tells us Move the invocation into the parens that contain the function , but I don't see the need.

Edit: The answers are too cool. ~function , an alternative to JSHint , as well as jQuery preference for (/***/)(); and Crockford's explanation! I thought that I was going to just get the answer "they are the same."
You guys decide the best option with upvotes, and I mark it.

+62
javascript closures comparison jslint anonymous-function
Jan 08 2018-12-12T00:
source share
3 answers

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

Please note that + and ! minifiers will also work and are sometimes used to save the size character:

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

EDIT

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

 -function() { var foo = 'bar'; }(); ~function() { var foo = 'bar'; }(); 
+48
Jan 08 2018-12-12T00:
source share

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

You can hear him discussing this in this video :

I think it looks stupid because we are saying that this is all an appeal, but we got these things hanging outside of it, looking like ... balls for dogs.

He suggests that parentheses inside help the reader understand that the entire operator is an expression of a function , not a declaration.

+38
Jan 08 2018-12-12T00:
source share

No, I do not believe that there is any difference. I personally prefer the former (and jQuery et al., It seems like I agree), but they both work the same in each core under test.

In addition, JSLint is sometimes too strict. JSHint may be a little better in this regard.

+10
Jan 08 2018-12-12T00:
source share



All Articles