Question 01 / 31

Why does the local variable log undefined?

Topic: Declaration instantiationDifficulty: Foundation

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

undefined

Why 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.

Specification references

JavaScript Code EditorDirectly edit or paste custom code
Step 0 of 0
←→StepSpaceRun
Press → (Step) or Space (Run)
Phase 1: Compilation(Hoisting & Memory Setup)
➔
Phase 2: Execution(Line-by-line Evaluation)
Execution Step Breakdown

Press "→" / click "▶" to step line-by-line, or press "Space" / click "▶ Run" for auto-play.