Hint
Local var declarations shadow the outer variable from the BEGINNING of the function — not just from where they appear.
var a = 1;
function test() {
console.log(a);
var a = 2;
console.log(a);
}
test();
console.log(a);undefined 2 1
Explanation: var a inside test() is hoisted — it shadows the global a from the start. First log: hoisted undefined. Then assigned 2. Global a stays 1.
Key Insight: Local var declarations shadow the outer variable from the BEGINNING of the function — not just from where they appear.