Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I declare my self-calling function?

I've seen self-calling functions in Javascript written like this:

(function () {
    // foo!
})();

But I've also seen them written like this:

(function () {
    // bar!
}());

Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?

One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:

function () {
    // shut the front door! saved two characters right there!
}();

It hurts readability a good deal though.

like image 821
Richard Neil Ilagan Avatar asked Sep 06 '12 16:09

Richard Neil Ilagan


2 Answers

First:

There is, like you assumed, absolutely no difference between the first two version of your self-invoking anonymous function. No browser klinks, quirks, just comes down to personal preference (Douglas Crockford calls the latter form "dog balls" by the way).

Second:

function() {
}()

will not work by design, since that statement creates a function statement/declaration. You need a function expression to immediately invoke itself. To create a function expression you can do multiple things. Putting the whole statement into parenthesis is one way, but you could also write

!function() {
}()

or

+function() {
}

All of these operators will make an expression.

like image 154
Andre Meinhold Avatar answered Oct 28 '22 00:10

Andre Meinhold


The first two are identical, but if I remember correctly, one of them is preferred by jsLint (I think it’s the second).

The third raises a syntax error in most interpreters, but there are other variants:

!function() {
    alert('I’m executing myself!');
}();

var noname = function() {
    alert(noname); // undefined!
}();

​ You can replace the ! with a + or - ( None of them will make Crockford happy )

like image 21
David Hellsing Avatar answered Oct 28 '22 00:10

David Hellsing