Table of Contents

Javascript - Global (Object|Namespace|window)

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:

See below the declaration section for examples.

Variable Declaration (Set)

Html script

Example of global variable definition:

var bar = "global variable declaration with the var keyword at the top of a script";
console.log(bar);
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);
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