3

Possible Duplicate:
Location of parenthesis for auto-executing anonymous JavaScript functions?
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?

I have seen the javascript anonymous functions written two different ways:

(function(){

})();

and

(function(){

}());

I have always thought the top one to be correct, and had never encountered the bottom one until now. I think this probably makes no difference at all but I thought I shoud be sure. Is there any difference between the two or are both ways equivalent?

Community
  • 1
  • 1
CRice
  • 12,279
  • 7
  • 57
  • 84

2 Answers2

2

They're equivalent.

The opening parenthesis is the important bit - it's the one that helps the parser figure out that what's coming is a function expression rather than a function declaration.

See http://kangax.github.com/nfe/ for an explanation of the difference.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Did I just have a déjà vu or have you answered a same question with this same answer – Esailija May 09 '12 at 11:00
  • @Esailija umm, if I did, I don't remember it... – Alnitak May 09 '12 at 11:01
  • 2
    lols, it's this one :D http://stackoverflow.com/questions/5938802/are-function-and-function-functionally-equal-i/5938902#5938902 I remember cos I upvoted you for it. It even has the same italics. – Esailija May 09 '12 at 11:04
  • 2
    @Esailija oh yeah :blush: You have a good memory - that answer was a year ago today! ;-) – Alnitak May 09 '12 at 11:06
0

Oohh....... This was just for fun.....


They are equal, but use this shorted closure way instead: (Twitter uses it!)

!function(){

}();

You'll save many characters. 1 each time.


But I prefer to use this one that I think it's more readably:

(function(){

})();

than:

(function(){

}());
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123