JavaScript: Correct way to define global variables

We know that what global variables or constants are, these are fields which are accessible application wide. In java, it is done usually done using defining “public static” fields. Here by adding final keyword, we can change the global variable to global constant. So easy, right?

But what about javascript? These scripting languages don’t have these access modifiers etc., so what are our options?

javascript jquery

I faced a similar situation in my regular work hours and came to know that defining global variable in traditional javascript way can break in production code. Traditional way is:

var iAmGlobal = "some val"; //Global variable declaration

//Any place in other part of code

function doSomething()
    //iAmGlobal = "changed value";
    alert(iAmGlobal); //I am accessible here too !!

These type are declaration are in practice from long time and for some less fortunate mates, it result in famous “Object doesn’t support this property or method” error in java script. If you remember there is an IE bug with “var a = foo” only declaring a global for file scope. This is an issue with IE’s notorious broken interpreter.

So, what’s correct way to declare global variable in javascript then?

Correct way to declare global variable in JavaScript

The proper way is to use window object. And use the syntax like this:

var window.iAmGlobal = "some val"; //Global variable declaration with window.

//Any place in other part of code

function doSomething()
    alert(window.iAmGlobal); //I am accessible here too !!
    alert(iAmGlobal); //I am accessible here too !!

By defining globals this way, you will make JavaScript more robust and reliable.

Important points:

  1. Define global variables with window keyword in form of “window.VAR_NAME”
  2. You can access the variable with “window.VAR_NAME” or directly “VAR_NAME”
  3. Do not use other variables with same name otherwise it may cause unwanted results

That’s all folks on this topic.

Further reading:

Happy learning !!


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.