Question 01 / 14
Why does the local variable log undefined?
Topic: Declaration instantiation
A var declaration inside a function creates a local binding before its assignment is evaluated.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
Predict the output. Does the function read the outer a, or its own not-yet-assigned local a?
var a = 10;
function fn() {
console.log(a);
var a = 20;
}
fn();Reveal the answer and explanation
Expected output
undefinedWhy this happens
Declaration instantiation hoists the var a inside fn before the function body runs, creating a local a binding that starts out undefined.
That local binding shadows the outer a for the entire function body, so ResolveBinding finds the local a first and never reaches the outer environment.
The assignment var a = 20 only runs on the next line, after the log has already executed, so console.log(a) prints undefined even though an outer a with the value 10 exists.
What this question tests
- var hoisting
- local shadowing
- function-scoped declarations
Runtime assumptions
The result is the same in a classic script or inside a module in any modern JavaScript environment.