I don't understand global variables in Javascript.

Discussion in 'JavaScript' started by googling1000@yahoo.com, Jun 4, 2009.

  1. #1
    My midterm is coming up. That's why I really need to understand this.
    I thought this was going to be a simple task, but so far it is not.

    I thought global variables can be modified in any function, and the value would be changed accordingly even when you're using it outside of that function, but this simple code has been giving me a headache.

    <html>
    <head>
    <script>

    var tree = null; //global variable

    function putInTree(value,tree)
    {
    if (tree == null)
    {
    tree = value;
    alert(tree); //this prints out 15 just fine
    }
    //there will more to this function, but right now, I only want to show this code is already not working.
    }
    </script>
    </head>

    <body>
    <script>
    putInTree(15,tree);
    alert(tree); //alert yields an error. It's complaining that tree is null
    //I was hoping to see tree get set to 15
    </script>
    </body>

    </html>


    Can you help explain why this is not working?

    I know there are 2 ways of passing values: by values and by references.

    Maybe I'm confused (sorry it has been a long time since I last saw this), but I thought as long as you are working with a global variable, when the value got changed, it will be consistent through out the whole program.

    I'll really appreciate if someone can help me with this.
     
    googling1000@yahoo.com, Jun 4, 2009 IP
  2. googling1000@yahoo.com

    googling1000@yahoo.com Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I figured it out. I guess I'll answer my own question just in case this is helpful for someone in the future.

    I saw this one site that pointed out what's wrong with a program similar to mine. It says:

    The variable myName is declared both globally outside of the function, and locally as the function parameter. Variables declared as function parameters have local scope. The myName variable on the first line is a global variable. The variable myName declared as a parameter of the function is a local variable only visible within the alertThisName function.

    var myName = "estelle"; // global
    alertThisName("jonathan");

    function alertThisName(myName){ // local
    alert(myName); // alerts "jonathan"
    }

    alert(myName); // alerts "estelle";
     
    googling1000@yahoo.com, Jun 4, 2009 IP
  3. Sleeping Troll

    Sleeping Troll Peon

    Messages:
    217
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yup!, Had my own go around with this one in the middle of an ajax call! I don't see why things have to be this way, are they protecting us from stupidity, like we are going to mistakenly use a global var as a function parameter? I can think of of few ways that could be very useful!
     
    Sleeping Troll, Jun 4, 2009 IP