1

While writing a javascript course for some coworkers, I accidently discovered an alternative syntax for self-invoking function. Does anyone know about it, is there some specifics to it ? I wasn't able to find documentation about it.

CODE : classic syntax

    (function(){
      console.log("I'm self-invoked!");
    })();

alternate syntax

    (function(){
      console.log("Me too!");
    }());

Thanks for the hints !

Dave Loepr
  • 946
  • 1
  • 7
  • 13
  • 3
    It works exactly the same way; the parentheses are only necessary to prevent it from being parsed as an statement (a unary operator would also work). What don't you understand? – SLaks Aug 26 '13 at 14:59
  • @SLaks you don't understand... The parentheses makes it an eager execution, not parsing. Parsing is done during compilation time, not execution time. –  Jun 08 '19 at 20:01
  • @PauliSudarshanTerho: No; parentheses never affect execution beyond shaping the parse tree. The parentheses are necessary to prevent a syntax error from parsing it as a statement. – SLaks Jun 12 '19 at 14:14
  • That was better explained –  Jun 12 '19 at 19:21
  • What I mean about eager execution is that this set `x` instantly to the value instead of function to give it later; `let x = (function(){return 123})()` –  Jun 12 '19 at 19:35

1 Answers1

2

The two are identical in meaning.

In both, the ( at the start symbols the start of an expression. This indicates the start of a function expression which we intend to invoke. Finally we invoke it. The difference is subtle and should not matter at all, let's explore it:

(function(){
  console.log("I'm self-invoked!");
})();

Here, ( is to tell the compiler it's the start of an expression, the compiler evaluates the expression (a function expression in this case) and then invokes it (outside the expression).

(function(){
  console.log("Me too!");
}());

Here - the invokation pattern ( () ) is part of that very expression.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504