JS: 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 JS: let Declaration]

[see JS: var Name Scope]

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

First, here's clarification of terms:

Behavior:

  1. declared and assigned → good.
  2. declared and unassigned → has default value of undefined.
  3. undeclared and assigned → implied global variable. (not exactly the same as declared global variable. Their configurable attribute's value is different.)
  4. undeclared and unassigned (and accessed) → ReferenceError.

Global Variable = Property of Global Object

Global variable is just property of the global object. [JS: the Global Object]

In web browser, the global object is window.

var xx = 3;
console.log (window.xx); // 3
console.log (window.xx === xx); // true

[see JS: Object Overview]

[see JS: 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
console.log (window.yy === yy); // true

Another example. This time inside a function.

function f () { x = 4; return 1; }
f();
console.log(x); // 4

Difference Between Implied Global and True Global Variable

[see JS: Property Attributes, writable, enumerable, configurable]

// 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 , 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); // true

JS Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Reference
  5. DOM Scripting
  6. SVG
  7. Blog