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