6

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?

7
  • 2
    Maybe for every reusable module that has nothing to with the app? Most prominent example: jQuery. Commented Aug 7, 2013 at 16:10
  • 1
    That's why I specified in the initial question "for a single Javascript application." Commented Aug 7, 2013 at 16:11
  • 2
    You mean "more than one global variable per standalone module"? Actually I don't see a reason to expose any global variable from your main app routine :-) Commented Aug 7, 2013 at 16:13
  • Sure. If we're playing the semantics game then that's what I mean. And the one global variable exposed in the example would be myGlobalApp Commented Aug 7, 2013 at 16:15
  • How does this feel like to you APP.domObjects.tables.dataTables.getFirst() a bit unwieldy? How big is your application and how much are you exposing the global namespace? I'd prefer to break it out into a few objects over one mammoth object. Your call. Commented Aug 7, 2013 at 16:18

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Typically libraries for client side Javascript each take at least one global because it would not be cool to require the user to use a module library.

0 global variables is a possibility in ES6 with first-class modules.

2 Comments

So Prototype.js with its many global functions is a notable exception?
@Bergi what are you implying? My post says that typical library will expose at least one new global
0

I would say the general rule that applies to Javascript and for that matter any other language is to minimize the case for global variables. I'm sure there are cases when more than one global variable is necessary but this generally should be avoided as much as possible. When building a library like jQuery you usually only need to expose one point of entry into that libraries functionality.

Also, global variables pollute the Javascript namespace and this could lead to collisions with other people's code.

2 Comments

"I'm sure there are cases when more than one global variable is necessary" -- I would argue that concretely identifying such a case (or generally defining such a class of cases) is the crux of the OP's question.
Maybe perhaps one case is you're relying on a third party library that is expecting your page to have some global callback into your code. I'm not suggesting this is a good idea, but if you rely on this third party library, or perhaps it's legacy, then this would be one example but obviously situational.
0

The only circumstance in which I've exposed multiple globals was for an app that would run multiple instances of itself each of which needed a reference to a single unified resource for use by onclick callbacks. Even in that case, with a little extra effort I could have kept the resource contained within the app and not needed the extra global.

So in short, on rare occasion it's useful / quick & dirty, but never necessary.

1 Comment

An onclick callback should indeed use local references only. Polluting the global namespace with handlers really needs to be avoided.
0

Does anyone know of an instance case where multiple global variables would be necessary?

Global variables are never necessary, any JavaScript code that uses global variables can be rewritten so that it doesn't.

Even in your example global variables aren't necessary, you can instead use a self-executing function as shown below:

(function(arg1, arg2) {
    var init = function (args) {...};
    var methodOne = function () {...};
    var methodTwo = function () {...};
    var propertyOne = 'string for example';

    init(arg1);
    init(arg2);
})(arg1, arg2);

Obviously libraries will often expose a global variable for using that library, for example jQuery creates the global variables jQuery and $. But for a single JavaScript application, global variables are never necessary.

3 Comments

What if you needed to invoke some javascript functionality from a mobile application that embeds a webview? What then?
@Bergi: True, but if the question is, can it be done without new global variables, then the answer is yes (although it isn't pretty). window.Object.myJSONPHandler = function(d) { ... }; Then have the JSONP call wrapper be Object.myJSONPHandler.
The only problem I see with this implementation is that (in a DOM manipulation type script) it requires either tailoring the script to a specific page, or writing HTML to conform to a script. I prefer the approach of writing a more widely implementable script and calling from inside <script>...</script> when and where needed. It seems the best DRY approach in my mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.