As we know var declarations get hoisted but with undefined value:
console.log(a); // undefined
var a = 2
function foo() {
console.log(a);
}
function bar() {
var a = 3;
foo();
}
var a = 2;
bar(); // 2
Wy does it log 2 instead of undefined ?
Why var a's value became magically accessible before it's declaration ?
You're calling bar() after you initialize the variable, so it's not undefined any more.
See this simpler example:
function foo() {
console.log(a);
}
foo(); // a is not yet initialized, prints undefined
var a = 2;
foo(); // a is now initialized, prints 2
Hoisting just makes the variable declaration available (so you don't get an "Undefined variable" error). The initialization is just an assignment that happens in the normal order.