Global Variables in JavaScript

Every tutorial that I've seen describes that to create a global variable you have to declare it outside the function.

var myvar = 5;
function myFunction()
   alert(myvar); // 5
}

And this is the way I've been doing it for years. The problem is, I've never been particularly happy about this. It never felt self contained. Then I thought, "Hey, why not just attach it to the window object?" I almost feel like an idiot for not having thought of this sooner and I suspect you JavaScripters out there are thinking "well, duh".

function setValue()
{
    window.myValue = "test";
}

function getValue()
{
    alert(window.myValue); // "test" (assuming setValue has run)
}

A quick search via Google revealed just how "in the dark" I've been. It turns out that when a global variable is set, it's added to the window object!

var myValue;
function setValue()
{
    myValue = "test";
}

function getValue()
{
    alert(window.myValue); // yup, it's "test"
}

Got any other quick JavaScript tips? Who knows what else I've been missing.

Published May 06, 2005 · Updated September 17, 2005
Categorized as JavaScript
Short URL: http://snook.ca/s/362

Conversation

26 Comments · RSS feed
Jonathan Fenocchi said on May 06, 2005

Other tips? Seldom, if ever, is the eval() method necessary. I see people using it all the time to declare variables, and while I would much rather use an array, if you really find it necessary to dynamically name a variable, the following code is not the way to do it:


var change = “1”;
eval(“var some”+change+“= \”value\“”);

You should use this instead:


var change = “1”;
window[“some”+change] = “value”;

I’ve tested this in terms of speed and found that, when processed 10,000 times, the first method requires ~250 milliseconds to process. That might not seem like much, but it is a lot when compared to the sixteen (yes, 16) seconds that it took to process the second code 10,000 times. As you can see, this is the optimal way to do it. Hope this helps.

Garrett Dimon said on May 06, 2005

Not to be overly pedantic, but global variables should kind of be a last resort. This is the case with almost any programming language really. It's kind of like playing with fire.

This isn't meant to be condescending or anything, I just wanted to help. Here's a good explanation.

There's all sorts of cases where it might make sense, but you should definitely only use them with caution.

Damn, I love your comment form.

David ODonnell said on May 12, 2005

Garrett, what you say is generally true for server-side programming languages, but in javascript nothing is really "global" because they are only in scope for the lifetime of the page.

@jonathan - i love document.getElementById('id'); but I suppose you already know that one ;-)

Garrett said on May 12, 2005

David - You're right, but I still shy away from them because I tend to lean on the side of purist.

Plus, as everybody is getting on the AJAX bandwagon, pages can get fairly complex, and even only being in scope for the lifetime of a page can cause some accidental problems if you aren't extremely careful. I just stay on the safe side, that's all.

FYRe said on January 01, 2006

With declared global variables, how do I set them as an id for (Eg. a checkbox).

----------------------------------------------
eg:
<script language="JavaScript">

var num1 = 0;

function thisIsAFunction()
{
<input type="checkbox" id="num1">
num1++;
}

function thisIsAnotherFunction()
{
.....
}
</script>
----------------------------------------------

By setting the globally declared variables as an ID to the checkbox, I could then access the checkbox based on the ID from another function.

Can anyone help?

dj said on June 28, 2006

How can you avoid using so-called globals in situations like this ...

For instance, I have an array of values that I need for some widget on the page. The user can click a button and retrieve new values from the server (using "AJAX") and these are inserted into the array and the widget is updated.

Whether it's the widget or a "global" that holds the array, one of these will need to be "global."

Finally, I'm using "global" in quotes because it's not really global. As this page says, your new variable becomes part of the window object.

Mr. Ignition said on July 23, 2006

Global variables are hard too avoid in JavaScript. People can say they're bad and all but who here can look at the source for their site and not have any global JS variables?

Jonathan Snook said on July 23, 2006

You can always contain your code down to just one global variable. In the case of this site, all my custom code is contained in the SNOOK variable.

randomguy said on November 28, 2006

Thanks, this tip helped me a lot!

Roger said on November 29, 2006

I admit to being a novice with JavaScript, but... so far, not a single example that I've found on Google of changing a value of a global var by means of a function has ever worked.

Prashant said on February 21, 2007

how to access the global variables from javascript in jsp page

Richard said on March 05, 2007

Hi guys,

I am an experienced developer with just a basic understanding of Javascript (enough to do client validation etc) but for the most part, most of my dev is on the server side.

My question: I have a global ActiveXObject that I loose everytime I post to the server? Is there ANY way to persist the state of the javascript global variable object on the client side during a round trip to the server?

I suspect I'm going to have to use a frameset? Anyother ideas?

Thanks!
Richard

Jonathan Snook said on March 05, 2007

@Richard: that's a definite dilemma and you've got a few things you can do:

  1. Use cookies to store state from page to page
  2. send the state information back to the server and include it in the rendered view
  3. use ajax to prevent a page refresh from occurring
  4. the frameset or it's cousin, the iframe
Richard said on March 05, 2007

Jonathan - Thanks for the response!

It's an AcitveX Object (.ocx) that implements a VIOP phone system on the client side so persisting the object in either cookies or at the server wont work in my situation.

I have no experience with Ajax yet and time to implement is a push. I don't want to use framesets but I think that's going to be the best option at the moment.

How many hours do you think it will take to ramp up on Ajax and after hearing more, do you still think that would be a good choice now that you have more details. I wouldn't mind learning Ajax - it appears to be a good way to get at server data without all the "perceived" round trips.

Thank you for confirming the needed direction.

Thanks again,
Richard

Jonathan Snook said on March 05, 2007

@Richard: based on your description of this ActiveX object, it seems like you need the ocx to be continually loaded. Going Ajax may be fairly quick depending on how you have things structured now. For example, some of the libraries can serialize a form and submit a POST request in just a couple lines of code.

Richard said on March 06, 2007

Jonathan,

After reading your response yesterday I broke out a Javascript book and read up on ajax. I also found an article you did on webreference.com which I found to be very helpful.

I had some miss conceptions. I think you are correct. I'm working on the ajax implementation now, I will let you know how it goes.

If I can keep the ActiveX object alive, all I need to do is send some simple string values to the server then display a couple simple return values. Ajax should do this with ease!

Thanks again,
Richard

Test said on August 15, 2007
text

but other than that

testvoid <script language="javascript">alert('hello')</script>

Shahzad said on November 11, 2008

I am looking for a global variable that is inter-script accessible. Something like:


< script language="JavaScript" >
   var interscriptVariable = 0;
< /script>

< script language="JavaScript">
//some other js file.
  function accessInterScriptVariable()
  {
      interscriptVariable = 1;
  }
< /script>


However I haven't been able to do so... any knows how to do this or is it possible?

Karim said on February 16, 2011

Hello Everyone, Although this is an old discussion but I would also like to ask question same as above. As if you have declared global variable and assigned it locally within a function, is it possible to call that local variable assigned as global within a function to again get the values globally in another script? I am having issues with doing such so, and can't find a good example to do so.

Any help in such instance will be appreciable.

Thanks,
Karim

x said on February 16, 2011

x

HH said on February 16, 2011

try this(repair '['):
[script type="text/javascript">
function aaa(){alert('aaa'+globvar);}//this works
[/script>
[script type="text/javascript">
var globvar=123;
aaa();
zzz();
[/script>
[script type="text/javascript">
function zzz(){alert('zzz'+globvar);}//this fails
[/script>

Rakesh said on March 15, 2011

Hello, I found this post usefull,.. .and then began to think how to delete the variable from the window object.. and i came across "delete"

delete window.myValue;

alert(window.myValue); // undefined

Endel said on March 22, 2011

Hello there,

I get stuck about sharing variables between frames from different domains.

It's impossible, right?

Jonathan Snook said on March 22, 2011

@Endel, that's correct. It is not possible to directly share variables between frames from different domains. There are ways around it, such as using Flash with properly configured crossdomain.xml file. Alternatively, many modern browsers allow for cross-domain ajax requests.

Russell Bicknell said on April 09, 2011

Global variables are actually the default in JavaScript. The keyword var is actually what causes the variable you are assigning to be placed in the local scope. If you want to declare a variable in the global scope from within any function, just omit the var keyword:

(function () {
x = 5;
})();
alert((x * 10)); // alerts "50"

This is really bad practice though, so refrain from doing so if at all possible. Littering the global scope with variables specific to your code can cause problems with other libraries (which hopefully follow this rule themselves). There's almost always a way to easily and cleanly avoid this situation. As a last resort, you can enclose the code that requires this global variable in a closure and declare it as local within that scope; in this way, the variable that used to be 'truly' global (a property of window) is now 'global' to the code within that closure. For example:

(function () {
var x = 5;
alert((x*10)); // alerts "50"

// All code here can access x as if it were 'global'.
});

alert(x * 20); // This line throws an error because x is not defined here.

Paul said on May 05, 2011

theres no open brace on your first example.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.