I was wondering if you could take a look at the code below that i have found in a book:
Code:
var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
When the function f is called, the first alert shows underfined and the second shows 1. The books says this happens because "i
nside 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."
I have a problem understanding how it works. My question, is at what stage, the local variable overwrites a global variable? At the stage of defining the function or calling it? I just want to have a clear picture in my heads what is going on. thank you very much.