Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts

    global variables

    Code:
    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?

  • #2
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.....

  • #3
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ah, dur, of course!

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

  • #4
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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 for a discussion on such matters.

  • #5
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Interesting. Thanks!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •