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 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problem in a global variable inside of a function

    Hello,

    I've always thought that variable inside of a function are always local,but recently, I've discovered that Variable can be global inside of a function if we don't use the keyword "var". Anyway, I've tried this JS code but it didn't work. Normally, it should work if we follow the previous rule. Here's the code:
    <script>
    Function x()
    {
    a = 5;
    }
    alert(a);
    </script>

    I can't figure out what's wrong :/

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,462
    Thanks
    23
    Thanked 634 Times in 633 Posts
    First JS is case sensitive so Function x(){} won't run, but function x() will.

    Next when the page loads the alert('a'); will run and make an alert, but alert(a); will not run cause a is not a variable. NOTICE THE QUOTES.
    And it will not run when the function is called because the function ends at the '}' and nothing after that will run.

    This:
    Code:
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    
    <body>
    <button onclick="x();">PUSH</button>
    <button onclick="y();">PUSH Again</button>
    <script>
    function x(){
    	a = 5;  // set the global variable
    }
    function y(){
    	alert(a);  // now the alert will work because the variable is set
    }
    </script>
    </body>
    </html>
    If you push buttons in sequence you will get an alert, but after reloading this and hitting 'PUSH Again' you will get nothing because you haven't set the variable.
    Last edited by sunfighter; 06-07-2014 at 05:55 PM.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."


  •  

    Posting Permissions

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