I have this piece of code
var a = 5;
function woot(){
console.log(a);
var a = 6;
function test(){ console.log(a);}
test();
};
woot();
i'm expecting 5 and 6 as an output, but i've got undefined and 6 instead.
Any thoughts?.
Variable declarations are hoisted to the top of the scope in which they appear. Your code is interpreted like this:
var a; // Outer scope, currently undefined
a = 5; // Outer scope, set to 5
function woot(){ // Function declaration, introduces a new scope
var a; // Inner scope, currently undefined
console.log(a); // Refers to inner scope 'a'
a = 6; // Inner scope, set to 6
function test(){ console.log(a);} // Refers to inner scope 'a' (now 6)
test();
};
woot();
When you declare a variable inside a function, that variable will shadow any variable with the same identifier that has been declared in an ancestor scope. In your example, you declare a in the global scope. You then declare another variable with the same identifier in the scope of the woot function. This variable shadows the a that you declared in the global scope.
var a inside woot shadows (supercedes) the global variable a with a local variable a, even before the var line. The var line is lifted ["hoisted"] to the top of the function where it appears, as James shows in his rewrite. But it's only the declaration, not the initialization, that is hoisted, so when a variable is declared with var, its initial value is undefined, and it only gets another value as of an assignment (or initialization). More: Poor, misunderstood varvar from the var a inside woot you will no longer shadow the outer a so any reference to a in there will be referring to the a you declared outside woot.The variable declaration (var keyword) is hoisted in the scope of your woot function, making it a local variable (shadowing the global variable a). It will be initialised as undefined, and return that value until you assign to it.
at the time of:
function woot(){
console.log(a);
..the a doesnt exist yet! if you want to use the outer a you need to call it like:
console.log( window.a );
Remove the a you have already in function and you can use, relaxed now, that console.log(a); which will refer to outer one (since there's no in your function anymore)
Otherwise, use console.log( window.a ); to differentiate the two alphas.
5. What are you asking for? Do you need it to be5?