Search code examples
javascriptdesign-patternsanonymous-functioniife

Immediately-Invoked Function Expression (IIFE) vs not


I see a lot of code like:

var myApp ={};
(function() {
    console.log("Hello");
    this.var1 = "mark";     //"this" is global, because it runs immediately on load.  Caller is global
    myApp.sayGoodbye = function() {
        console.log("Goodbye");
    };
})();

Which causes the anonymous function to execute immediately. But what is the advantage of this, compared to just putting the code inline?

var myApp ={};
console.log("Hello");
var1 = "mark";     
myApp.sayGoodbye = function() {
    console.log("Goodbye");
};

Apparently it's to do with scope of the function, but as the function is anonymous and called by window, it's scope (i.e. this) is global, no?


Solution

  • Usually, you would have this :

            var myApp ={};
            (function() {
                console.log("Hello");
                var var1 = "mark";  
                myApp.sayGoodbye = function() {
                    console.log("Goodbye");
                };
            })();
    

    The main difference is that var1 doesn't clutter the global namespace. After this call, var1 is still the same than before (generally undefined).

    As var1 can only be accessed from the function defineds in the closure, it is said "private".

    Apart avoiding possible causes of conflicts, it's just cleaner not to keep global variables when useless.

    Here, you don't have a local variable but a global one defined as this.var1. It's probably a bug, or the reason would be found elsewhere in the code.