Self-Calling JavaScript Functions

Question:

(function(a){
    alert(a);
}(1));


(function (a) {
    alert(a);
})(1);

What is the difference between these functions?

Or here's from Stefanov's example:

var result = (function () {
 return 2 + 2;
}());

(function () {
 alert(‘watch out!’);
})();

Answer:

In general, there is no difference.
Douglas Crockford considered that the entry:

(function () {
    //body
}());

Is correct, and the notation:

(function () {
    //body
})();

Wrong and disparagingly calls her "dog balls".


Therefore, use the one that you like best (I, for example, agree with Douglas, although the second option is not at all annoying).
For example, in Perl slogan generally states that everything should have several notation paths.
Why is JS worse? 🙂

Scroll to Top