Table of Contents

About

The global namespace is the top space of Javascript that contains the variables.

In a browser, it's known as the window.

Defining global variables pollutes the common namespace shared by everyone, introducing the possibility of accidental name collisions. Globals variable definition go against modularity

Global variables are also automatically properties of the global object (window in browsers, etc.)

Management

Detection

Whenever a name is used, the interpreter walks the scope chain backwards looking for a var, let, const statement for that name. If none is found, that variable is assumed to be global.

Accessibility

You are writing code in the global space located:

  • at the top of a script
  • in properties of the this keyword at the top of a script
  • in properties of the window object in a browser.

See below the declaration section for examples.

Variable Declaration (Set)

Html script

Example of global variable definition:

  • The common way is to declare a variable with the var keyword at the top of a script
var bar = "global variable declaration with the var keyword at the top of a script";
console.log(bar);
  • Beware of variable leaking in the global scope as without the var keyword, the variable is declared in the global space.
function scope(){
    bar = "global variable declaration without the var keyword in a function";
    // Becareful, if you redeclare the same variable later with the var keyword, 
    // thanks to variable hoisting the below statement will placed at the top of its scope 
    // and the variable will not be considered global anymore but local
    // var bar = "local variable declaration with the var keyword in a function"; 
}
// Run the function to run the variable declaration
scope();
console.log(bar);
  • The global object is also accessible via this at the top of a script. Adding a property to it will declare a global variable.
this.foo = "global object property declaration via the this keyword";
console.log(foo);

Window

In the browser, the global object is accessible via the window object

window.foo = "global object property declaration via the window object";
console.log(foo);

List

Devtool

With the devtool, open the console and type window.

Global Namespace Web Console Firefox

Script

The first 10 variables of the global object:

function propertyRepresentation(o,v){
  this.variableName = v;
  this.type = typeof o[v];
  this.variableValue = o[v];
}

globalVariables = [];
counter = 0;
globalObject = this;
for (prop in globalObject) {
  globalVariables.push(new propertyRepresentation(globalObject,prop));
  counter++;   
  if (counter >= 10){
     more = { more: "... on a total of "+Object.keys(globalObject).length }
     globalVariables.push(new propertyRepresentation(more,"more"));
     break;
  }
}

console.log("The first 10 variables of the global object:");
console.table(globalVariables);

Documentation / Reference