Global variables in Javascript

Global variables are evil. Although possibly nifty for very small programs it quickly clutters the global namespace and increase the risk for name collisions as are program grows larger. The risk for collisions are even greater when using different libraries and widgets.

There are three ways to define a global variable in Javascript.

The first way is to declare the variable outside of any function.

var myGlobalVar = value;

The second way is to assign it as a property to the global object, which in web browsers are the window object.

window.myGlobalVar = value;

The third way is to use it without defining it. In this case it doesn’t matter if it’s inside of a function or not. This is called implied global.

myGlobalVar = 'Hello world';

A great way to minimize the use of global variables is to store them all in one global object. By doing this you can keep all you variables and functions in one place, greatly reducing the risk for name collisions.

// Define your global object
var myObj = {};
// Add property (variable) to it
myObj.myVar = 'Hello world';
// Add method to it
myObj.myFunctions = function() {
    // Do cool stuff
};

The Javascript language was designed with global variables like this to make it easy for beginners to start coding. The side effect being that it’s easy to forget to define a variable and thereby creating bug that are hard to discover. So do yourself a favor and avoid global variables whenever possible.

About the author

Gabriel Svennerberg is an independent Interaction/UI Designer and Web Developer living in Sweden. When he's not busy building web application designed for humans, he writes about all things web on his site In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress.
  • http://www.heavyworks.net Jan Seidl

    Yeap, objects are awesome. I think the JS frameworks are giving a new step to the language. OOP is being more and more present into a language that people underestimated for years in a row.

    Like happened to C when became C with Classes (C++), is JavaScript evolving to JS++ ?

  • http://www.svennerberg.com Gabriel Svennerberg

    Yes, a lot of things has happened with Javascript the last few years. It has changed status from being considered a second grade language to proving to be really useful. I too think the js frameworks have helped making it more useful and popular.

    The object model in Javascript is really cool. But it’s also widely misunderstood since it depends on prototypal inheritance which is not well understood by most people coming from languages with classical inheritance.

    The more I learn about Javascript, the more I like it. No doubt it contains a lot of serious flaws, like global variables. But once your recognize them you can avoid them.

  • http://mankzblog.wordpress.com Mats

    Om du gillar globala variabler kanske denna sidan är av intresse… :)

    http://mankz.com/code/globalcheck.htm

  • http://www.svennerberg.com Gabriel Svennerberg

    Mats: Well I’m not particularly fond of Global variables since they are EVIL, but that’s a pretty interesting tool you’ve built. Some libraries really do clutter the global namespace.

    Thanks for the link!

  • http://www.pixelovers.com/no-conviene-usar-variables-globales-javascript-544325 Anonymous

    [...] Global variables in Javascript [...]

  • http://derek1906.site50.net Derek

    You solve my problem!! thx! thx! thx! thx! !!!!!!!

  • MP

    Demonstrating how to declare global variables is only half the job! The other half is accessing them which you failed to demonstrate!

    ie: In the case of strings…

    message:myGlobalVar;

    message=myGlobalVar;

    message=’myGlobalVar’;

    message=”myGlobalVar”;

    message= var.myGlobalVar;

    Etc, etc… or should we come back next month for the second exciting episode of “Javascript… one bit at a time!”

    Javascript, is crude and archaic enough without all these internet “teachers” wasting people’s time with drips and drabs!

    If you’re gonna teach do it right or get off the airways so we can find someone who’ll CLOSE OFF a job!

  • Jagan

    var form1= document.jaganForm;
    function1()
    {
    var txt= form1.text1.value;
    }
    function2()
    {
    var txt2=form1.text2.value;
    }
    Is this ryt?