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 !!
    //OR
    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: http://stackoverflow.com/questions/4862193/javascript-global-variables

Happy learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

16 thoughts on “JavaScript: Correct way to define global variables”

  1. You shouldn’t use the ‘var’ keyword for this example because of the ‘window’ is already defined as the ‘Window’ object.

    Reply
  2. var window.iAmGlobal = “some val”;

    So what is need of var here i think correct way is

    window.iAmGlobal = “some val”;

    Reply
  3. I need help to generate auto generated code for buyer like when i select India from struts2 template its code come IND01, IND02… If in case i select China code comes like CHN01, CHN02 n so on.. I am developing s/w in struts2 and hibernate 3 but i think I think we need to use javascript for this but i dont know how to use it.. Please help me out for this

    Reply
  4. My point is: if in your first example you were to alert the window.iAmGlobal variable it would work perfectly fine. There’s no need to further confuse the issue by incorrectly telling people this is how you globally scope a variable, which they shouldn’t even be doing in the first place.

    Your 300 word post would be better served teaching hoisting, rather than ” Holy shit! var duh === var duh”.

    Reply
    • I do not write only for experts, rather my readers are beginners and medium level experts with some hand-on. I really need to put some words to make them clear. Anyways, I got your point.

      Reply
  5. Indeed this issue does occur when you have your code split between multiple files in IE and you require them to communicate between each other. I think this IE issue isn’t preset in more recent versions so its not something that is a must have. If you’re in an enterprise environment with required support for old versions of IE this information can be useful.

    Reply
  6. No. None of that is correct. Your first example is the equivalent of your second when run in a browser because of variable hoisting. When you use the keyword var, JavaScript will assign that variable within the current scope. In your first example that scope is the top most, which in a browser is window.

    There are tons and tons of examples of this available online, is one of the key facts thou must understand about JavaScript. If you don’t grok hoisting, your applications functioning properly is just pure dumb luck.

    Reply
    • Thanks for your input. I understand this but the thing is behavior of browsers (specially IE) are always surprising. I myself have faced problem what I mentioned in “IE bug with “var a = foo” only declaring a global for file scope”.

      So, I am concluding my learning here as always go with “windows.VAR_NAME”. Yes they are identical in a fair world, but we don’t live in that.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.