How to declare a global variable in JavaScript?

To declare a global variable in JavaScript, assign a value to a field in the window object.

window holds all global variables and it is accessible from anywhere in your JavaScript:

function declareMyGlobalVar() {
  window.myGlobalVar = 'Hello World!';
}

function printMyGlobalVar() {
  console.log(window.myGlobalVar);
}

console.log(window.myGlobalVar); // undefined

declareMyGlobalVar();

console.log(window.myGlobalVar); // Hello World!
printMyGlobalVar(); // Hello World!