Skip to main content


Showing posts from April, 2009

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:varsomeVar=5;varrunMe=function(){alert(someVar);varsomeVar=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 &…