View Full Version : global variables

07-08-2004, 10:51 PM
var d = document;
var f = d.forms[0];

function doSomething() {
f.style.marginRight = "3em";

That function is retarded, but the point is to illustrate what I tried to setup global variables that I reuse frequently in scripts, but it doesn't seem to work. I read that all variables are global in JS unless declared within a function, in which case they are local to that function. So what is wrong with the above then?

Willy Duitt
07-08-2004, 11:00 PM
Because you are trying to reference an element (forms[0]) which is not yet present on the page.....

BTW: It is better to keep all variables local in scope if at all possible and with experience, it is indeed possible.....

07-08-2004, 11:48 PM
Ah, dur, of course!

However, why is it better (aside from fixing idiotic coder error) to keep variables local? Why even have globals then?

Willy Duitt
07-09-2004, 12:13 AM
A few reasons using local variables are better than using global variables are:

1] Up to 26x's faster than using global variables
2] Have less chance of conflicts with other scripts
3] Do not fill memory with garbage often not removed

You can also look here (http://www.codingforums.com/showthread.php?s=&threadid=33161) for a discussion on such matters.

07-09-2004, 12:16 AM
Interesting. Thanks!