How to declare global variables in JavaScript

You may have heard or read that global variables are a bad idea. However sometimes you may need a global variable badly. To use them properly it’s best to understand the concept of scope in JavaScript. Let’s take the following example to understand the local and global scope:

Local and global scope

var SomeVar = 1; // This is a global variable

function MyFunction() {
    alert (SomeVar);      // We can use SomeVar inside the function because it is global
    var OtherVar = 2;   // We can use OtherVar only inside the function because it is local

alert(OtherVar); // This will throw a "is not defined" error
Unfortunately it’s not always possible (or desired) to declare a variable outside all functions. One example I can think of, is when you use jQuery and you are inside the scope of $(document).ready(function(){code here}); The trick here is to attach the variable to the window object and access it from there as well. This is illustrated in the following example:

Using the window object

window.MyVariable = 0;

function FunctionOne(){
  window.MyVariable = 1;

alert (window.MyVariable); // Value is 0


alert (window.MyVariable); // Value is 1
Please note that a variable which is set outside all functions is attached anyway to the window object. So once you set a global variable you can always access it using window.MyVariable. Similarly a variable defined using window.MyVariable can be accessed using just MyVariable.

Follow us for more great posts in the future.

Facebook Twitter

Get posts in your email