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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Did I just have a déjà vu or have you answered a same question with this same answer
@Esailija umm, if I did, I don't remember it...
lols, it's this one :D stackoverflow.com/questions/5938802/… I remember cos I upvoted you for it. It even has the same italics.
@Esailija oh yeah :blush: You have a good memory - that answer was a year ago today! ;-)
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(){

}());

5 Comments

Not necessarily easier to understand though... in general, I think it's better to use code minifiers.
It is far more important for code to be obvious then it is for it to be short.
no, don't use that way - it's not as easily recognised.
Do NOT use !function... it seriously hurts readability. And it doesn't matter if Twitter uses it or not.
to be honest they all read the same to me, am I the only one who have developed a blind spot for this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.