At a quick glance, what do you think the value of '
y' will be at each alert?
alert 1: 1', '
alert 2: 1', and '
alert 3: 2'; thinking that the global value from before the function would carry into the function until it is reassigned.
The answer is instead '
In the first pass, the function is parsed and all local variables are moved to the top of the function. And the second pass runs it. So in reality, the script looks like this by the time it is run:
<script src="https://gist.github.com/1176159.js"> </script>
Notice that '
var y', and not '
var y = 2' was moved to the top of the function. By declaring an unset local variable at the top of the function, the global '
y' variable is overwritten, causing '
alert 2' to be undefined.