title: Need help understanding how the below IIFE code works
body: <p>I recently came across this javascript code in a competitive site and couldn't understand how this pretty much works.</p>
  
  <pre><code>var a= 1;
  (function(){
      console.log(a);
      var a = 2;
      console.log(a);
  })();
  </code></pre>
  
  <p>I expected the output to be..</p>
  
  <blockquote>
    <p>1 2</p>
  </blockquote>
  
  <p>But to my surprise, the original output was..</p>
  
  <blockquote>
    <p>undefined
    2</p>
  </blockquote>
  
  <p>Can someone please explain how it works? Thanks in advance.</p>