Is there a difference between the syntax of Self-Invoking-Functions?

4

I've learned three ways to write Self Invoking Functions , Immediately-Invoked Function Expression (IIFE) , and I wondered if there was any difference between them.

(function () {
    console.log("Olá");
})();

(function () {
    console.log("Olá");
}());

! function () {
    console.log("Olá");
}();

void function () {
    console.log("Olá");
}();

OBS. The question is relative to the Self Invoking Functions and not the difference for "normal" functions.

    
asked by anonymous 05.06.2015 / 15:45

1 answer

6

All versions end up doing the same thing, which is calling the anonymous function, and it's more a matter of taste. I prefer the 2 (function(){ ... }()) version because I think it gets brighter with the parentheses wrapped around the "magic" part. I also do not recommend version 3 because it is more rare and can confuse other people.

One suggestion is to put an extra semicolon at the beginning to protect against the case of forgetting to put the semicolon on one of the lines that comes before.

var x = foo

(function(){ ... }());

In this case Javascript will parse the program as if foo were a function:

var x = foo(function(){... }());
    
05.06.2015 / 15:56