title: Hoisting and variable scope
body: <p>Would someone help explain why the two snippets of code below print out different results? </p>
  
  <p>The difference is inside the conditional statement.  In the first, there is a local variable assignment of 'Jack' to name, and the conditional  is truthy (meaning !name evaluates to true).  In the second, the same name 'Jack' is assigned but to the global variable name, but the conditional is falsy (!name is false).  My question is, if all else is the same, why would the first conditional be true and the second is false if what is changed is <em>inside</em> the conditional body? </p>
  
  <p>My only explanation is that the body of the conditional is read by the JS interpreter <em>first</em>, which is how it determines whether <code>name</code> is global/local, whether the variable declaration needs to be hoisted or not, and finally, the different name values logged.  </p>
  
  <p>Shouldn't the conditional boolean be evaluated first before even starting to interpret its body?  Then in both cases, variable 'name' would be evaluated as 'undefined'... Any help would be greatly appreciated!  </p>
  
  <p>There are a few really good resources about hoisting/scope contexts but I'm not finding one that specifically answers this question.</p>
  
  <p><a href="http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/" rel="nofollow">http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/</a></p>
  
  <pre><code>var name = "Paul"; 
  function users () {
      if (!name) {
          var name = "Jack";  //&lt;== difference is here, *inside* conditional body
      }
      console.log(name);
  }
  users(); //outputs "Jack"
  </code></pre>
  
  <p>vs. </p>
  
  <pre><code>var name = "Paul"; 
  function users () {
      if (!name) {
         name = "Jack";  //&lt;== difference is here, *inside* conditional body
      }
      console.log(name);
  }
  users();  //outputs "Paul"
  </code></pre>