title: javascript variable is undefined
body: <p>First , let's see the code.</p>
  
  <pre><code>var a=0;
  b=1;
  document.write(a);
  function run(){
      document.write(b);
      var b=1;
  }
  run();
  </code></pre>
  
  <p>I think the result is <code>01</code> .but in fact , The result is <code>0undefined</code>. </p>
  
  <p>Then I modify this code.</p>
  
  <pre><code>var a=0;
  b=1;
  document.write(a);
  function run(){
      document.write(this.b); //or document.write(window.b)
      var b=1;
  }
  run();
  </code></pre>
  
  <p>Yeah, this time it runs as expected. <code>01</code> . I can't understand, WHY?</p>
  
  <p>More interesting, I modify the code again .</p>
  
  <pre><code>var a=0;
  b=1;
  document.write(a);
  function run(){
      document.write(b);
      //var b=1;       //I comment this line
  }
  run();
  </code></pre>
  
  <p>The result is 01.</p>
  
  <p>So , Can anyone explain this?</p>
  
  <p>Thanks for share your viewpoints.
  I simplify this code </p>
  
  <pre><code>b=1;
  function run(){
      console.log(b); //1
  }
  </code></pre>
  
  <p>two:</p>
  
  <pre><code>b=1;
  function run(){
      var b=2;
      console.log(b); //2
  }
  </code></pre>
  
  <p>three:</p>
  
  <pre><code>b=1;
  function run(){
      console.log(b); //undefined
      var b=2;
  }
  </code></pre>