JS: Global Variable

By Xah Lee. Date: . Last updated: .

Global Variable

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]

Here's clarification of terms:

Behavior:

Global Variable is Property of the 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(window.xx === 3);
console.log(Reflect.has(window, "xx"));

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

Undeclared Variable (Implied Global)

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);
console.log(Reflect.has(window, "yy") === true);

// all true, in browser
// undeclared variable, become global property, even inside function

function f() { zz = 4; }

f();

console.log(zz === 4);
console.log(Reflect.has(window, "zz"));

/*
all return true, in browser.

in deno, undeclared var is an error inside function
*/

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);

💡 TIP: Never Use keyword “var”

The scoping of var is complex, and implicit global property, and global variable, are all bad.

Always use JS: let Declaration or JS: const Declaration.

BUY ΣJS JavaScript in Depth

JavaScript, keyword var