javascriptfunctionscopeidentifieriife

Why bother passing arguments to IIFEs when you can just write the expression directly in the body?


I've seen the next way of writing self-invoking functions:

(function (app) {
    app.foo = {
        bar: function(){}
    };
}(App));

Where App is a global object.

I wonder, why do we need to pass App as a param into a function? Why don't just use this:

(function () {
    App.foo = {
        bar: function(){}
    };
}());

I see only one advantage of using the first way. If we for some reason rename the App object, then we can easily rename the param in brackets and our code will work as it works. But in case of the second way we will probably need to rename App in all places where we use it.

Are there other differences?


Solution

  • It means that the contents of the function – with regards to the app identifier – are agnostic to the global (or parent) scope.

    One of the scenarios in which this is done is, for example, with jQuery, when you don't want to assume that the jQuery object is called $ (e.g. if no-conflict mode is on), but you do want to call it by that name. Passing it through an anonymous function like this (i.e. (function($) {})(jQuery)) allows you to generate a locally-scoped alias that doesn't interfere with the external meaning of the name $ in the parent/global scope.