Possible Duplicate:
Redeclare JavaScript Variable
I have the next piece of code:
var i = 11;
alert(i);
function a(){
alert(i);
var i = 2;
alert(i);
}
a()
The second alert(i) (inside the function) produces undefined. I’m guessing it has to do with the way JS engine runs through the code – maybe it doesn’t store variables first, before going throught the lines?
Anyway I thought that this is not a problem is JS because it supports hoisting. I probably got it wrong – does anybody care to explain?
Thanks!
JavaScript does indeed hoist declarations to the top of the scope in which they occur, but assignments happen at the place you would expect them to. Your code is effectively parsed like this:
This is detailed in the spec. Upon entering a new execution context, the following happens: