0

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.

Mahesha999
  • 22,693
  • 29
  • 116
  • 189
  • 3
    Because of the comma operator, http://es5.github.io/#x11.14 – Ian Jul 15 '13 at 14:19
  • I think u have pointed me to right direction, but am not able to understand the specs :( my bad; I think thats lexical description which I find difficult to grasp; what does it say? – Mahesha999 Jul 15 '13 at 14:24
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator , and don't use document.write in jsFiddle. – Givi Jul 15 '13 at 14:28
  • thanks @Givi I got it from MDN, its just comma separated expression list, right? – Mahesha999 Jul 15 '13 at 14:31
  • Exactly! *"The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand."* In your case it's just return undefined from anonymous function expression. – Givi Jul 15 '13 at 14:36

0 Answers0