Chapter 6. Avoid Globals

The JavaScript execution environment is unique in a lot of ways. One of those ways is in the use of global variables and functions. The default JavaScript execution environment is, in fact, defined by the various globals available to you at the start of script execution. All of these are said to be defined on the global object, a mysterious object that represents the outermost context for a script.

In browsers, the window object is typically overloaded to also be the global object, so any variable or function declared in the global scope becomes a property of the window object. For example:

var color = "red"

function sayColor() {
    alert(color);
}

console.log(window.color);              // "red"
console.log(typeof window.sayColor);    // "function"

In this code, the global variable color and the global function sayColor() are defined. Both are added to the window object as properties even though they weren’t explicitly set to do so.

The Problems with Globals

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.

Naming Collisions

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

Get Maintainable JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.