Multiple Global Variables in Javascript

javascript

Solution

I don't think it's ever strictly necessary to have multiple globals - JavaScript objects can be arbitrarily nested, and can often be used like namespaces.

window.AwesomeModule = {
    app: {
        ...
    },
    util: {
        ...
    }
};

In fact, if your app is not made to be reusable (i.e. it's just user-facing), you could probably not leak any globals.

(function() {
    var AwesomeModule = { ... };
    // Do whatever you want - create DOM nodes, bind to events, etc
    // Just don't bind anything to window
})();

A more interesting question is whether having multiple globals would ever be genuinely useful, and I'd say that it depends on your development style. For example, if we look at C# and .NET in general, we can see that the entire framework (more or less), namespaces and all, are housed beneath a top level namespace `System`.

Of course, if you're going to be making some huge JavaScript app with multiple components, I would definitely not recommend such a nested structure (besides being possibly unwieldy, JavaScript object attribute lookups have a definite runtime cost, which could add up).

...Regardless, though, the JavaScript landscape is not so well-pruned. A simple check for global attributes yields around 56 items on my machine on an empty page (running Chrome).

var i = 0;
for (var prop in window) {
    if (window.hasOwnProperty(prop)) {
        i++;
    }
}

So, although we can and should minimize our own global usage, the JS environment as it stands today (especially when using external libraries) often involved the proliferation of globals. Example: StackOverflow has around 144 total globals.

Problem

This isn't a specific problem, but a more theoretical question. Is there ever a good reason to expose multiple global variables for a single Javascript application? I can see using, and often use myself, a single global variable to name an object or class containing the app so that it can be recalled multiple times (example below), but I can't think of any case when any additional global variables couldn't be replaced by object properties. Example where an exposed variable makes life easier (using a closure, it couldn't be recalled): ``` var myGlobalApp = { init: function (args) {...}, methodOne: function () {...}, methodTwo: function () {...}, propertyOne: 'string for example' }; myGlobalApp.init(arg1); myGlobalApp.init(arg2); ``` Does anyone know of an instance case where multiple global variables would be necessary?

Original source