0

While studying the closers topic I stack up with one simple question.

For example these code work:

!function (){
    console.log(true)
}();

(function (){
    console.log(true)
})();    // doesn't work when 'use strict' is defined

var varName = function (){
        console.log(true)
}();


These code doesn't work:

function (){
    console.log(true)
}();

function funcName (){
    console.log(true)
}();


Question: What is this simple rule that stand by behind the self-invoking functions? Or they simple need to have their own lexical environment and cant exist as general object?

Adrian
  • 273
  • 2
  • 13
  • You need to break the previous line's statement. So adding `;` in front of the second set of codes will also work. Check it out. – Praveen Kumar Purushothaman Apr 18 '16 at 14:47
  • The key is where in the expression the `function` keyword appears. If it's the very first thing, then it's no longer an expression - the parser assumes it's going to parse a function declaration statement instead. When `function` appears anywhere else, it's an expression component. – Pointy Apr 18 '16 at 14:47
  • 4
    @PraveenKumar no they won't. The first one is incorrect because a function declaration statement requires a name, and the second is incorrect because a function declaration statement cannot be followed by an invocation (the `()` at the end). – Pointy Apr 18 '16 at 14:48
  • @Pointy Thank you a lot for the explanation! :) Maybe you can recommend some interesting topic about function declaration syntax rules or anything useful that will help to discover more about these cases? – Adrian Apr 19 '16 at 14:31
  • 1
    @Andrew there are only a few such ambiguities, with `function` and `{` being two that I can think of now. The parsing rules resolve those ambiguities with fixed rules, not any sort of "smart" examination of the source. Thus, if the parser thinks that a new statement is about to start, and it sees `function`, then that's *always* a function declaration statement, and if it doesn't look like one then that's a syntax error. – Pointy Apr 19 '16 at 14:34
  • 1
    @Pointy Thank you a lot for explanation, at the first look I didnt get what you was actually trying to explain me, a little later I found this article http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife ,after reading it, I found your explanation pretty easy and clear, hope it will help someone else, too :) – Adrian Apr 20 '16 at 21:08

0 Answers0