As far as I know the following declaration will not add any value to the variable aa
:
var aa = undefined;
function a () {
var aa;
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // should add to the globle scope (window Object)
bb = 12; // should add to the globle scope (window Object)
}
console.log(aa);
console.log(aa); // should be 11
console.log(bb); // should be 12
}
Now if I want to use access the vars aa
and bb
, I can get access only bb
not aa
.
My question is why aa
cannot be accessed from outside, because in the declaration I haven't assigned any value to it and it is still undefined?
Thank you.
Look at my comments
var aa = undefined; // global scope
function a () {
if(true) { // useless
var aa; // declare aa in the function scope and assign undefined
// to work on the global aa you would remove the above line
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // reassign the local aa to 11
bb = 12; // assign 12 to the global var bb
}
console.log(aa); // aa is 11
}
console.log(aa); // still in the function scope so it output 11
console.log(bb); // should be 12
}
console.log(aa) // undefined nothing has change for the global aa
For more read this great Ebook