Javascript Tip: Avoid Global Variables

Creating globals is considered a bad practice in general and is specifically problematic in a team development environment. Globals create a number of nontrivial maintenance issues for code going forward. The more globals, the greater the possibility that errors will be introduced due to the increasing likelihood of a few common problems.

The potential for naming collisions increases as the number of global variables and functions increase in a script, as do the chances that you’ll use an already declared variable accidentally. The easiest code to maintain is code in which all of its variables are defined locally.

The global environment is where native JavaScript objects are defined, and by adding your own names into that scope, you run the risk of picking a name that might be provided natively by the browser later on.

Ensuring that your functions don’t rely on globals improves the testability of your code.

Accidental Globals

One of the more insidious parts of JavaScript is its capacity for creating globals accidentally. When you assign a value to variable that has not previously been defined in a var statement, JavaScript automatically creates a global variable.

This code represents a very common coding error that accidentally introduces a global variable.

The problem is compounded when you’re trying to create a local variable with the same name as a global variable. For example, a global variable named count would be shadowed by the local variable count in the previous example. The function then has access only to the local count unless explicitly accessing the global using window.count.

The One-Global Approach

You may be thinking at this point, “How is it possible to write JavaScript without introducing any globals?” Although it is technically possible through some clever patterns, this approach is usually not feasible or maintainable in the long run.

The best approach is to try to have as small a global footprint as possible by agreeing to create only one global object.

The one-global approach is used by all popular JavaScript libraries:

  • YUI defines a single YUI global object.
  • jQuery actually defines two globals, $ and jQuery.
  • Dojo defines a single dojo global object.

The idea behind the one-global approach is to create a single global with a unique name and then attach all of your functionality onto that one global.  So instead of creating multiple globals, each would-be global simply becomes a property of your one global.

This code has a single global, myGlobal, to which all of the other information is attached.

Leave a Reply

Your email address will not be published. Required fields are marked *