Search code examples
javascriptnamespacesobject-literal

How to return object literal in JavaScript


I'm trying to wrap a JavaScript object literal in a self executing anonymous function. The first code example below works fine, but the second doesn't and I'm not really sure why?

Works:

(function(){
    return MyApp = {
        init: function() {
            console.log('MyApp init');
        }
    }
})();

Doesn't Work:

(function(){
    var MyApp = {
        init: function() {
            console.log('MyApp init');
        }
    }
    return MyApp;
})();

As I understand things, the SEAF should execute and immediately return. That's why the first example returns MyApp as an object I can interact with. I thought assigning MyApp to a variable inside the SEAF and then returning it would do the same thing but in:

Uncaught ReferenceError: MyApp is not defined

Why?


Solution

  • Since the result of your SEAF (better named IIFE) is not used anywhere. It doesn't really matter what the function returns. Now compare

    (function(){
        MyApp = {…}
    })();
    

    with

    (function(){
        var MyApp = {…}
    })();
    

    The difference is that in the second function your variable is preceded by a var keyword which makes it local to the IEFE, while in the first function it is an implicit global (which you should avoid). That way, the second snippet doesn't assign to anything in the global scope, and accessing MyApp later from outside will fail with the error.

    Better return some value that you then assign to a globally declared variable:

    var MyApp = (function(){
        return {…};
    })();