I was learning about JavaScript Immediately Invoking Function Expression (IIFE) from here.
In this Ben very well explains why directly invoking function doesn't work:
function(){ /* code */ }(); // SyntaxError: Unexpected token (
//since when the parser encounters the function keyword in
//the global scope or inside a function, it treats it as a
// function declaration (statement), and not as a function
// expression
So what all we need to ensure is that parser interprets it as a function expression but not as a function declaration.
The obvious way is immediately invoking function - putting function definition in parenthesis (and thus forcing parser to interpret it as a function expression) and then again putting parenthesis after that
(function(){ /* code */ })(); //or
(function(){ /* code */ }());
However the author explains other places where expressions are expected which forces function definition to be interpreted as function expression but not as declaration:
var i = function(){ return 10; }();
true && function(){ /* code */ }();
!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();
However I dont understand why function definition in below is forced to be interpreted as an expression:
0, function(){ /* code */ }();
So below actually calls the function:
0, function () { document.write("<h1>Hello World!!</h1> <br />") }(); //Hello World!!
The working JSFiddle.