Is there a difference beyond the syntax between Self-invoking-Functions?

Asked

Viewed 134 times

5

I learned three ways to write Self Invoking Functions, Immediately-Invoked Function Expression (IIFE), and I was left with a doubt whether beyond the syntax there is any difference between them.

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

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

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

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

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

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 version 2 (function(){ ... }()) because I think it’s clearer with the parentheses wrapped around the whole "magic" part. I also do not recommend version 3 because it is more rare and may confuse other people.

One suggestion is to put an extra semicolon at the beginning of everything to protect yourself against the case someone forgets to put the semicolon in 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(){... }());
  • Thanks, I also prefer the second syntax, but it’s more because it is valid in Jslint. That tip from semicolon before I knew it, it is quite useful and I’ve had problems with the previous line without them.

  • Speaking of jslint, I much prefer Jshint. It’s a jslint Fork with much more functionality and much more customizable.

  • I use Jshint for my projects, but at work Lint is more mandatory...

  • 1

    Aff, These people are late :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.