Understanding Global & Local Scope in Javascript
<p>I've been learning Javascript using <a href="http://www.packtpub.com/object-oriented-javascript/book" rel="nofollow">Object-Oriented JavaScript by Stoyan Stefanov</a></p>

<p>He offers an example comparing global and local scope:</p>

<pre><code>var a = 123;
function f() {
    alert(a);
    var a = 1;
    alert(a);
}
f();
</code></pre>

<p>Looking at this example, I expected the first alert to be '123' and the second alert to be '1'.  Lo and behold, Stoyan says:</p>

<blockquote>
  <p>You might expect that the first alert() will display 123 (the value of
  the global variable a) and the second will display 1 (the local a).
  This is not the case. The first alert will show “undefined”. This is
  because inside the function the local scope is more important than the
  global scope. So a local variable overwrites any global variable with
  the same name. At the time of the first alert() a was not yet defined
  (hence the value undefined) but it still existed in the local space.</p>
</blockquote>

<p>The explanation was not clear to me, how can the local variable overwrite the global variable in the first alert? Any other/different explanations would be appreciated.</p>
