SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Jun 2010
    Posts
    446
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    defining variables

    How can x be a variable in this script if it's not declared using "var"?

    HTML Code:
    <html>
    <body>
    
    <p id="intro">Hello World!</p>
    
    <script type="text/javascript">
    x=document.getElementById("intro");
    document.write(x.firstChild.nodeValue);
    </script>
    
    </body>
    </html>

  2. #2
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    JavaScript doesn't require explicit declaration of variables. Any var that is instantiated without a "var" statement belongs to the global scope. Any var instantiated _with_ the "var" statement belongs to the scope it was defined in.

    In your case, because you have assigned a value to "x", it is now a global var.

    e.g.:
    Code JavaScript:
    var x = 5;
     
    y = 2;
     
    function test() {
    	var y;
    	x = 10; //modifying the global
    	y = 8; //y is defined in side the method with "var", so it is local
    	z = 7; //also modifying the global
    }
    test();
    console.log(x); //10
    console.log(y); //2
    console.log(z); //7
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }

  3. #3
    SitePoint Evangelist
    Join Date
    Jun 2010
    Posts
    446
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Didn't know that. Thanks.


Bookmarks

Posting Permissions

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