Search code examples
javascriptiife

Why are parentheses required around JavaScript IIFE?


I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,

(function() {var msg='I love JavaScript'; console.log(msg);}());

works great, but

function() {var msg='I love JavaScript'; console.log(msg);}();

generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.


Solution

  • The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.

    http://benalman.com/news/2010/11/immediately-invoked-function-expression/

    For more detailed explanation please see:

    Advanced JavaScript: Why is this function wrapped in parentheses?

    HINT:

    The invocation operator (()) only works with expressions, not declarations.