5

I came across a strange behavior related to immediately-invoked function expressions.

var foo = function(){
    alert('foo');    
}

(function(){
})();

http://jsfiddle.net/tmh8hpum/

Run the above code and notice how the foo function is evaluated, but..

var foo = function(){
    alert('foo');    
};

(function(){
})();

http://jsfiddle.net/fwcst8w6/1/

Add a terminator to the function and it is no longer invoked.

I expected that the IIFE would only evaluate the code inside its own function body. Why does the IIFE cause the non-terminated function directly above it to be evaluated?

Even stranger, it only seems to be the function directly above it; run this Fiddle and note how only bar() is evaluated.

Payton Staub
  • 487
  • 3
  • 10
  • 4
    This is interesting question. The problem is that without semicolon the first example is interpreted as `var foo = function() {alert('foo');}(...)` where `...` is some arguments passed into IIFE (in this case `function() {}`). – dfsq Dec 31 '14 at 18:40
  • Yep, it's very obvious now that I see it. Regardless, I don't think this should be marked as duplicate. This question has a more searchable title than the duplicate and is a clearer example of the behavior. – Payton Staub Dec 31 '14 at 18:44
  • Sure, maybe you are right. I reopened it again. Related question on the same issue: http://stackoverflow.com/questions/23587441/javascript-strange-loading-sequence – dfsq Dec 31 '14 at 18:47

0 Answers0