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

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.

Scope Chain
Lexical Environment Chain: Inner Scope → Outer [[Scope]] → Global (GO)
No active scope chain
CALL STACKStack of Execution Contexts (LIFO)
LIFO Stack Frames
Global Execution Context (GEC)
▶ Active Frame
HEAP & MEMORY SPACEAllocated Objects (GO, AO, FunctionObjects, ER)
ECMAScript Heap Area
No objects in memory
Console Output
console.log(...) Stream
No output generated yet