Search code examples
javascriptself-invoking-function

Understanding the difference between self invoking functions statements


Please explain, why does this statement

function f(){}()

throw an exception, but absolutely the same thing inside of brackets

(function f(){}())

does not


Solution

  • The parser interprets the former as a function declaration and the later as a function expression.

    Why? To understand we need to look in section 11.1.6 and 12.4 of ECMA-262 3rd edition. Section 12.4 states that "an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration." This tells us that the function f(){}() must be a function declaration, and the () is invalid syntax. The reason this statement is an expression is because of the grouping operator in section 11.1.6 (aka the parenthesis) forces this function to be treated as an expresion.