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