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.

3
  • 3
    you have redefined aa to be in the function scope, and since you didn't assign a value, it has assigned undefined Commented Jun 14, 2013 at 6:32
  • You are redeclaring the variable aa in your function Commented Jun 14, 2013 at 6:35
  • @JonathandeM.: So do you mean undefined is the value that is being assigned to the variable? Commented Jun 14, 2013 at 6:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

So do you mean undefined is the value that is being assigned to the variable in my case?
yes the value by default is undefined unless you assign manually a value, var a = undefined is equal to var b; a === b
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.
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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.