Sub topic 6
Shadowing Variables in Inner Scopes
This chapter assumes you know how the scope chain resolves a name by walking outward from the current scope, and that you can tell function scope from block scope. Shadowing follows directly from those rules. When an inner scope declares a name that already exists in an outer scope, lookups from inside the inner scope stop at the inner declaration. The outer variable still exists and keeps its value, but code in the inner scope can no longer reach it by that name.
Shadowing is legal, sometimes useful, and a common source of quiet bugs. This chapter covers how it works, where it is forbidden, how it interacts with the temporal dead zone, and how to keep it under control.
The Basic Mechanism
Name resolution starts in the current scope and moves outward. The first scope that contains a binding for the name wins, and the search stops there. Shadowing is that rule seen from the outer variable's point of view.
const level = "global";
function outer() {
const level = "outer";
function inner() {
return level;
}
return inner();
}
console.log(outer()); // "outer"
console.log(level); // "global"Inside inner, the engine looks for level in inner's own scope and doesn't find it. It moves to outer's scope, finds level, and stops. The global level is never consulted. After outer returns, the global binding is unchanged, because shadowing creates a second, separate variable. Nothing is overwritten.
Kinds of Shadowing
Any declaration form that creates a binding in an inner scope can shadow an outer one. The table lists the common cases.
| Inner declaration | Scope it creates a binding in | Shadows an outer name when |
|---|---|---|
| `let` / `const` / `class` | Nearest enclosing block | Declared inside any block, function, or module nested in the outer scope |
| `var` | Nearest enclosing function (or script) | Declared inside a nested function |
| Function parameter | The function's parameter scope | The parameter name matches an outer name |
| Function declaration | Enclosing function, or enclosing block in strict mode | Declared in a nested scope |
| `catch (e)` parameter | The catch block | The catch parameter matches an outer name |
Block-level shadowing with let and const
Blocks are the most common place for shadowing in modern code.
const total = 100;
if (true) {
const total = 5;
console.log(total); // 5
}
console.log(total); // 100The two total bindings live in different scopes. Because const is block-scoped, the inner one disappears when the block ends.
Parameter shadowing
Parameters are local bindings, so a parameter with the same name as an outer variable shadows it for the whole function body.
const user = "admin";
function greet(user) {
return "Hello, " + user;
}
console.log(greet("guest")); // "Hello, guest"
console.log(greet()); // "Hello, undefined"The second call is a bug that shows up often. The caller forgot the argument, and the reader may assume user falls back to the outer "admin". It doesn't. The parameter exists either way, and its value is undefined. To fall back to the outer value, ask for it explicitly with a default parameter such as function greet(name = user), which also avoids reusing the name.
Loop shadowing
A for loop with let has a scope for its head, and the loop body is a separate block inside it. That means you can shadow the loop variable inside the body.
for (let i = 0; i < 2; i++) {
let i = "inner";
console.log(i); // "inner", printed twice
}This is legal, and the loop still runs twice because the increment updates the head's i. Nobody writes this on purpose. It usually appears when a body grows long and someone reuses a short name.
Where Shadowing Is Forbidden
Shadowing needs two different scopes. If two declarations would end up in the same scope, and at least one of them is let, const, or class, the engine throws a SyntaxError before any code in that script or function runs.
function sameScope() {
let a = 1;
// let a = 2; // SyntaxError: Identifier 'a' has already been declared
// var a = 2; // SyntaxError, same reason
}
function paramClash(b) {
// let b = 2; // SyntaxError: parameter and let in the same scope
{
let b = 2; // fine: a nested block is a different scope
console.log(b); // 2
}
}
paramClash(1);Remove the // from any commented line and the whole function fails to parse.
The var-through-a-block trap
The case that surprises people is var inside a block. A block does not contain var. The declaration hoists to the enclosing function or script. If that outer scope already holds a let with the same name, the two collide.
// Running this file throws:
// SyntaxError: Identifier 'x' has already been declared
let x = 1;
{
var x = 2;
}The author meant to shadow x inside the block, but var x actually belongs to the same top-level scope as let x. The reverse works: an inner let inside a block can shadow an outer var, because let stays in the block.
var y = 1;
{
let y = 2;
console.log(y); // 2
}
console.log(y); // 1var redeclaring var or a parameter
Two var declarations of the same name in one function are allowed, and they refer to a single binding. That is redeclaration, not shadowing. The same goes for var with the same name as a parameter: the var adds nothing, and the parameter keeps its value.
function keep(a) {
var a;
return a;
}
console.log(keep(5)); // 5Shadowing Meets the Temporal Dead Zone
A shadowing let or const takes over its name for the entire block, starting at the opening brace, not at the declaration line. Before the declaration runs, the inner binding exists but is uninitialized. Any read in that stretch throws, even when an outer variable with the same name would work fine.
let count = 10;
{
try {
console.log(count); // inner count is in its TDZ
} catch (e) {
console.log(e.name); // "ReferenceError"
}
let count = 20;
console.log(count); // 20
}The most common version of this mistake looks like an attempt to derive the inner value from the outer one:
let price = 50;
{
try {
let price = price * 2; // right-hand side reads the inner, uninitialized price
} catch (e) {
console.log(e.message); // "Cannot access 'price' before initialization"
}
}The right-hand side runs while the inner price is still uninitialized, and lookup stops at the inner binding without reaching the outer one. The fix is to use a different name, such as const doubledPrice = price * 2.
Reaching a Shadowed Variable
Inside the shadowing scope, the outer binding has no syntax that refers to it. JavaScript has no outer.x operator. There is one partial exception. Global var declarations and function declarations in a classic script become properties of the global object, so you can reach them through globalThis.
var siteName = "Main"; // global var, in a classic script
let siteMode = "dark"; // global let: not a global object property
function show() {
const siteName = "Local";
const siteMode = "light";
console.log(siteName, globalThis.siteName); // "Local" "Main"
console.log(siteMode, globalThis.siteMode); // "light" undefined
}
show();Run this as a classic script, such as a browser <script> tag or the browser console. In Node.js CommonJS files and in ES modules, top-level var is not global, so globalThis.siteName is undefined there too. Don't rely on this escape hatch. If inner code needs both values, give them different names.
Shadowing Built-ins and Globals
You can shadow global names that the platform provides, including name, status, event, length, and even undefined inside a function.
function risky() {
const undefined = 42; // legal in a function scope
let value;
console.log(value === undefined); // false
}
risky();At the global level, undefined is a non-writable property, so you can't reassign it there. Inside a function, a local declaration creates a new binding that shadows it. Real code rarely does this on purpose, but older libraries sometimes used (function (undefined) { ... })() to guarantee an untouched undefined. Shadowing name or status in browser code causes milder confusion, because those globals exist on window and some code may expect them.
When Shadowing Is Fine and When to Avoid It
Shadowing is acceptable when the inner meaning is local and obvious. Typical examples are a short callback parameter named item inside a function that also has an item, or a deliberately narrowed value in a small block.
Avoid it when:
- The two variables mean different things. Rename one so readers don't have to track which binding is active.
- The block is long. Readers lose track of where the inner declaration started.
- The inner value is derived from the outer one. That is exactly the case that triggers the TDZ.
- A parameter shadows a module-level setting that callers might expect as a fallback.
Linters can enforce this. ESLint's no-shadow rule reports any declaration that shadows an outer one, and no-shadow-restricted-names blocks shadowing of undefined, NaN, Infinity, arguments, and eval.
Exercises
Exercise
What does this code print, and why? let n = 1; function f() { console.log(n); if (false) { var n = 2; } } f();
Show answer
It prints undefined. The var n inside the if block hoists to f's function scope even though the block never runs, so it shadows the outer n for the whole function. When console.log runs, the local n exists but has not been assigned, so its value is undefined.
Exercise
Why does this throw, and how would you fix it while keeping the intent of doubling the outer value? const rate = 3; { const rate = rate * 2; }
Show answer
The inner const rate shadows the outer one from the start of the block, so the right-hand side reads the inner binding while it is still in its temporal dead zone, which throws ReferenceError: Cannot access 'rate' before initialization. Fix it by using a different name, for example const doubledRate = rate * 2.
Exercise
Which of these is a SyntaxError and which runs? (a) var v = 1; { let v = 2; } (b) let w = 1; { var w = 2; } (c) function g(p) { var p; } (d) function h(q) { let q; }
Show answer
(a) runs: the inner let is confined to the block and shadows the outer var. (b) is a SyntaxError: var w hoists out of the block into the same scope as let w. (c) runs: var redeclaring a parameter is allowed and does not change its value. (d) is a SyntaxError: let q and the parameter q are in the same function scope.