How to Declare a Global Variable in JavaScript

The two ways to declare a global variable in JavaScript, inside and outside of a function.

Published Categorized as JavaScript, Web & Code

In JavaScript, the accessibility of a variable is determined by its scope (W3Schools). As a general rule of thumb, a variable can have three scopes: block scope, function scope, and global scope.

Variables with block scoping are declared with the let statement, and can be accessed only within the block.

Variables with function scoping are declared with the var statement within the function, and can be accessed only within the function.

The question is, how do you declare a global variable?

How to Declare a Global Variable in JavaScript

There are two ways to create a global variable in JavaScript. One is to declare it outside of a function. In this case, it is automatically assigned a global scope. The other is to declare it as a property of the window object from inside a function.

From Outside the Function

A variable declared outside of a function automatically becomes a global variable:

// Declare global variable
var myName = "Jim";

// Reference variable within function
function printName() {
  console.log('Hey there! My name\'s ' + myName + '.');
}
printName(); // Hey there! My name's Jim.

From Inside the Function

To declare a global variable from inside a function, declare it as a property of the window object:

// Declare global variable inside function
function saveName() {
  window.myName = "Jim";
}

// Reference the variable outside the function
console.log('Hey there! My name\'s ' + myName + '.'); // Hey there! My name's Jim.

Once you’ve declared your variable as a property of the window object, you can reference it from inside and outside your function.

Just make sure to declare the variable before you reference it. Otherwise, you will come across the dreaded function not defined error.

Leave a comment

Your email address will not be published. Required fields are marked *