Question 02 / 14

What happens when a parameter and a local var share a name?

Topic: Lexical scope

A var declaration that names an existing parameter does not create a new binding — it reuses the parameter's binding.

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

Predict the output

Predict the output. Does the var a inside fn create a second binding, or does it just reassign the parameter a?

var a = 10;
function fn(a) {
    console.log(a);
    var a = 20;
    console.log(a);
}
fn(5);
Reveal the answer and explanation

Expected output

5
20

Why this happens

When fn(5) runs, the parameter a is bound to 5 in the function's environment before the body executes.

Declaration instantiation then processes var a inside the body. Since a is already declared as a parameter, hoisting does not create a second binding or reset it to undefined — the parameter binding is reused, so the first console.log(a) prints 5.

The following line, var a = 20, assigns 20 to that same binding, so the second console.log(a) prints 20.

What this question tests

  • parameter binding
  • var and parameter share a binding
  • no reset to undefined

Runtime assumptions

This behavior comes from declaration instantiation for functions and holds in any standard JavaScript engine, in both script and module code.

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