JavaScript: Global Variable

By Xah Lee. Date: . Last updated: .

Never Use Global Variable and “var Declaration”

Note: using global variable is a bad practice in programing, especially after JS2015 . Because it makes your code mysterious and harder to control. For example, imagine you work in a company in a project that has thousands lines of code spread over hundreds of files. it's very hard to know which variable has a value and in what file.

Global variable is a variable whose scope is whole program. That is, it has meaning anywhere in the software.

Global variable can be created by:

[see var Name Scope]

Every global variable name is also a global property name, and vice versa.

First, here's clarification of terms:

Behavior:

Global Variable = Property of Global Object

Global variable is just property of the Global Object .

In web browser, the Global Object is window. [see Browser Window Object]

var xx = 3;
console.log(globalThis.xx === 3);
console.log(Reflect.has(globalThis, "xx"));

/* [
all true in browser
all false in deno
] */

[see Object Overview]

[see Check Property Existence]

Undeclared Variable

When a variable is assigned but not declared, it is a global variable. This is sometimes called implied global.

yy = 3;
console.log(window.yy === 3); // true
console.log(Reflect.has(window, "yy") === true); // true

Another example. This time inside a function.

function f() {
  zz = 4;
}
f();
console.log(zz === 4); // true
console.log(Reflect.has(window, "zz")); // true

Difference Between Implied Global and True Global Variable

[see Property Attributes]

// difference between declared and undeclared variable

var x = 1;
console.log(Object.getOwnPropertyDescriptor(window, "x"));
// Object {value: 1, writable: true, enumerable: true, configurable: false}

y = 1; // undeclared
console.log(Object.getOwnPropertyDescriptor(window, "y"));
// Object {value: 1, writable: true, enumerable: true, configurable: true}

(Note: as of 2014-07-10, in Firefox, if you run code in JavaScript console, undeclared var's configurable property is the same as declared global variable (presumably for programer convenience). But in Google Chrome's JavaScript console, it behaves by spec.)

Accessing Undeclared and Unassigned Variable → ReferenceError

x;
// ReferenceError: x is not defined
// unassigned var has value of undefined
var y;
console.log(y === undefined);

JavaScript variable

BUY
ΣJS
JavaScript in Depth