1

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.

uber5001
  • 3,864
  • 4
  • 23
  • 44
me_digvijay
  • 5,374
  • 9
  • 46
  • 83

2 Answers2

1

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

Jonathan de M.
  • 9,721
  • 8
  • 47
  • 72
  • So do you mean `undefined` is the value that is being assigned to the variable in my case? – me_digvijay Jun 14 '13 at 06:40
  • yes the value by default is `undefined` unless you assign manually a value, `var a = undefined` is equal to `var b;` `a === b` – Jonathan de M. Jun 14 '13 at 06:43
  • Thank you for clearing my misconception. I always thought of `var a` as `nothing is there`. But now what I can understand is `there may occur a variable 'a' which is inside this scope but no value has been assigned to it`. Please correct me if I am wrong. – me_digvijay Jun 14 '13 at 07:05
  • `undefined` is a special value which means nothing has been defined. So not defining or defining undefined is kinda the same. About the scope here [a good ebook](http://bonsaiden.github.io/JavaScript-Garden/#function.scopes) – Jonathan de M. Jun 14 '13 at 07:18
0

Try removing var aa; from within your function.

What's happening here is function scope. You've declared aa as a local variable within function a. the local variable IS getting set to 11.

uber5001
  • 3,864
  • 4
  • 23
  • 44