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. Continue reading