title: Javascript scoping variables theory
body: <p>I have two example pages that are behaving differently and I would like to know why. To me they seem consistent with each other based one what I have gathered about scoping in javascript.</p>
  
  <p>1.html:</p>
  
  <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
  &lt;script type="text/javascript"&gt;
    function demofunction(x, y) {
      z=x+y;
    }
  &lt;/script&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
  &lt;title&gt;4-6.htm&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;h1&gt;Bad Scoping&lt;/h1&gt;
      &lt;script type="text/javascript"&gt;
      //&lt;![CDATA[
      demofunction(3, 2);
      alert(z);
      var z;
      alert(z);
      //]]&gt;
      &lt;/script&gt;
      &lt;p&gt;&amp;nbsp;&lt;/p&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>In this example, demofunction runs and sets the global variable z to 5. alert runs and since there is no z in scope it grabs the global scope and finds a z which is equal to 5, it alerts that. then a new local variable named z is defined. the second alert can see that local variable, but since it is undefined, it choses the global one and alerts 5 again.</p>
  
  <p>2.html</p>
  
  <pre><code>&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Bad Scoping&lt;/title&gt;
    &lt;script type="text/javascript"&gt;
    //&lt;![CDATA[
    first = 6;
    document.writeln('&lt;p&gt;first is ' + first + "&lt;/p&gt;");
  
    function letsSee() {
      alert(first);
      var first;
      first = 4;
    }
    letsSee();
    document.writeln('&lt;p&gt;but now first is ' + first + "&lt;/p&gt;");
  
    //]]&gt;
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>global first gets set to 6. letsSee() runs and the alert (if consistent) should see no local variable named first so it should alert the global variable 6. then a local first is defined, which is then set to 4. letsSee() exists and the last print prints the global first and shows 6 again.</p>
  
  <p>this does NOT happen though. what happens is that it shows 6, alert has undefined, and shows 6. my question is directed to why does it alert undefined rather than 6? if i comment the line inside letsSee for <code>var first;</code> i then see that it alerts 6 and then display's 4. this makes sense to me. but why does having that var first after the alert make a difference to what the alert call sees as the value? esp when it didn't make a difference in 1.html.</p>