Sub topic 6
Shadowing Variables in Inner Scopes
This chapter assumes you can declare variables with var, let, and const, and that you know how the scope chain searches outward from the current scope for a name. Shadowing is what happens when that search finds a match earlier than you expected.
What Shadowing Is
Shadowing happens when an inner scope declares a name that already exists in an outer scope. Inside the inner scope, the inner declaration hides, or "shadows", the outer one. The outer variable still exists and keeps its value. Code in the inner scope just can't reach it by that name.
Because the scope chain stops at the first match, the nearest declaration always wins.
let count = 10;
function report(count) {
if (count > 0) {
let count = "positive";
console.log(count); // "positive"
}
console.log(count); // 3 (the parameter)
}
report(3);
console.log(count); // 10This code has three separate count bindings:
| Where you read `count` | Binding found | Value |
|---|---|---|
| Inside the `if` block | Block-scoped `let` | `"positive"` |
| Function body, outside the block | Parameter | `3` |
| Top level | Script-level `let` | `10` |
A parameter counts as a declaration in the function's scope, so it shadows any outer variable with the same name.
Shadowing Is Not Reassignment
A common mistake is to think the inner declaration changes the outer variable. It doesn't. Leaving out the declaration keyword is what changes the outer variable:
let status = "idle";
function shadow() {
let status = "busy"; // new binding, outer untouched
return status;
}
function overwrite() {
status = "busy"; // no keyword: assigns to the outer binding
return status;
}
shadow();
console.log(status); // "idle"
overwrite();
console.log(status); // "busy"When you debug a value that "didn't change", check whether a let or const crept into the inner assignment. When a value changed unexpectedly, check whether a declaration keyword is missing.
Illegal Shadowing
Most combinations are allowed. A let or const inside a block can shadow an outer var. The reverse fails: a var inside a block cannot shadow a let or const from an enclosing block in the same function. The reason is that var ignores blocks and is scoped to the whole function, so it would collide with the outer let. The engine reports this as a SyntaxError while parsing, before any of the code runs.
try {
new Function("var x = 1; { let x = 2; }");
console.log("let shadowing var: allowed");
} catch (e) {
console.log(e.name);
}
try {
new Function("let x = 1; { var x = 2; }");
} catch (e) {
console.log(e.name); // "SyntaxError"
}new Function is used here only so the bad code can be parsed inside a try block. In ordinary code, the whole script would fail to load.
When Shadowing Hurts
Shadowing is legal and sometimes useful. For example, a short-lived result inside a block keeps its value from leaking out. It becomes a problem when the outer value is the one you meant to use. There is no syntax for reaching past a shadowing binding to the outer one. The fix is to rename one of the two variables.
Exercises
Exercise
What does this code log, in order? let user = "Ada"; function greet(user) { { const user = "Grace"; console.log(user); } console.log(user); } greet("Linus"); console.log(user);
Show answer
"Grace", then "Linus", then "Ada". The block's const shadows the parameter, and the parameter shadows the outer let. Each console.log stops at the nearest binding named user.
Exercise
Does function f() { const a = 1; { var a = 2; } } run? Why or why not?
Show answer
No. It throws a SyntaxError when parsed. The var is scoped to the whole function body, so it collides with the const a that is already declared in that same function scope.