Question 06 / 14

Why does var escape the if block?

Topic: Declaration instantiation

var is scoped to a function or script, not to an if block.

Solve it with the execution visualizerStep through every binding, function call, and console output below.

Predict the output

Both branches contain declarations. Which assignments actually run?

if (true) {
  var a = 1
} else {
  var b = 2
}

console.log(a)
console.log(b)
Reveal the answer and explanation

Expected output

1
undefined

Why this happens

Both a and b var bindings are created for the surrounding scope before the if statement is evaluated.

Only the true branch executes, assigning 1 to a. The false branch does not execute, so b keeps its initial undefined value.

Because neither binding belongs to the block itself, both names can be read after the if statement.

What this question tests

  • var scope
  • control flow versus declaration creation
  • unexecuted assignments

Runtime assumptions

Replacing var with let would create block-scoped bindings and change what can be read afterward.

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