JavaScript: Global Variable

By Xah Lee. Date: . Last updated: .

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

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:


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

[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; }
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

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

JavaScript variable

JS in Depth

JS in Depth

JS Obj Reference


JS in Depth

Basic Syntax

Value Types





Object and Inheritance



Iterable 🌟