It is because of what is called Javascript Hoisting, this is how javascript sees your code:
function foo() {
var b; // javascript hoisted this variable on top
console.log(b) // so here you see underfined
b = 2;
console.log(b);
}
Now because javascript hoised variable b
on top of function, your global variable b
was never used and hence statement immendiately after hoisted variable showed undefined
. So if you remove new declaration (var
keyword) from your function, you should still have access to global b
variable.
BTW, it is good practice to declare all your variables on top of function like:
function foo() {
var b = 2;
console.log(b);
}
To know more on the topic, see this: