Var's and closures

I have a tendency at times to take the 'var' statement as "Ok, now that we have reached this line, lets create this variable with this name". In reality though, it serves more for an identification than a procedural statement. To try to explain better, this is an issue I came across:
var someVar = 5;
var runMe = function(){
  alert(someVar);
  var someVar = 6;
  alert(someVar);
}
runMe();
Now, I thought this would alert '5' then '6'. However, it alerts 'undefined' and '6'. The Ecma-262 specification says the following in 12.2:
Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
If I'm reading this correctly, this means that the variable 'someVar' gets created as a local variable in function 'runMe' right when that function is invoked and before the var line is even executed.
I honestly can't remember why I needed to do this at the time. I think I just wanted to use one variable name to look at an old value and then a newly set value. The obvious way around this is to just use a different local variable name.

Comments