This question already has an answer here:
- Javascript function scoping and hoisting 16 answers
why does the following code segment generate the following output?
code segment:
var a = 10;
function(){
console.log(a);
var a = 5;
}
output:
undefined
Because variable is hoisted at top and in your function you have declared the variable var a = 5 which is same as following:
And in your function scope var is being declared it doesn't see global variable but local variable i.e. var a and which is undefined.