title: Why JavaScript declared variable is in the global object before initialization?
body: <p>I've stumbled upon a JavaScript variable behavior I could not explain.</p>
  
  <p>According to <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var" rel="nofollow">JS docs on var keyword</a> :</p>
  
  <blockquote>
    <p>The scope of a variable declared with var is the enclosing function
    or, for variables declared outside a function, the global scope (which
    is bound to the global object).</p>
  </blockquote>
  
  <p>Also it is known that global variables become properties of the global object - 'window' in the browser environments and 'global' in node.js
  This means if a variable is declared with a 'var' keyword inside a function it becomes local and does not get into the global object.</p>
  
  <p>This example proves it:</p>
  
  <pre><code>(function(){
      var t = 1;
      console.log(t in window, t); // outputs: false 1
  }());
  </code></pre>
  
  <p><a href="http://jsfiddle.net/WmH77/" rel="nofollow">jsfiddle link</a></p>
  
  <p>So far so good. However if variable is not initialized it does become a property of the window object despite the fact it is in the function scope.</p>
  
  <pre><code>(function(){
      var t;
      console.log(t in window, t); // outputs: true undefined
  }());
  </code></pre>
  
  <p><a href="http://jsfiddle.net/WmH77/1/" rel="nofollow">jsfiddle link</a></p>
  
  <p>Why does it happen ? Where can I learn the details of this behavior ? Regular tutorials don't seem to cover this.</p>
  
  <p>Thanks in advance.</p>
  
  <p>[EDIT]:
  Thanks to the Pointy it is clear now scope works as expected. I simply had a wrong understanding of the 'in' operator behavior. According to <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/in" rel="nofollow">'in' docs</a> it coerces left hand operand to the number or string and looks for such index or property name in the right hand object.
  So in the example one it was equal to</p>
  
  <pre><code>'1' in window
  </code></pre>
  
  <p>which was false</p>
  
  <p>and in the example two it was</p>
  
  <pre><code>'undefined' in window
  </code></pre>
  
  <p>which was true.</p>