View Single Post
Old 01-29-2013, 04:16 PM   PM User | #1
chickentulip
New Coder

 
Join Date: Oct 2010
Location: Toronto
Posts: 95
Thanks: 52
Thanked 0 Times in 0 Posts
chickentulip is an unknown quantity at this point
global vs local-Please help to understand the principle

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 "inside 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.
chickentulip is offline   Reply With Quote