JavaScript Global Variable


A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global:

var x = 5; // global

function someThing(y) {
  var z = x + y;
  console.log(z);
}

function someThing(y) {
  x = 5; // still global!
  var z = x + y;
  console.log(z);
}


function someThing(y) {
  var x = 5; // local
  var z = x + y;
  console.log(z);
}

A global variable is also an object of the current scope, such as the browser window:

var dog = “Fluffy”;
console.log(dog); // Fluffy;

var dog = “Fluffy”;
console.log(window.dog); // Fluffy

Example -