Variable Shadowing
Quick summary
You declared a variable with the same name as one in an outer scope — the inner variable hides the outer one, causing confusion.
Why this happens
Using the same variable name in nested scopes
Reusing common names like i, x, or count in inner blocks
Naming a local variable the same as a global or parameter
Minimal example
let x = 10;
function test() {
let x = 20; // Shadows outer x!
console.log(x); // 20, not 10
}
test();let x = 10;
function test() {
let innerX = 20; // Distinct name
console.log(x, innerX); // 10, 20
}
test();The inner let x = 20 shadows the outer let x = 10. Inside the function, x refers to the local 20. Renaming the inner variable makes the code clearer and avoids confusion.
How to diagnose
Check if the variable value is different from what you expect
Look for variables with the same name in different scopes
Use your editor's 'find all references' to see all declarations
How to fix
Rename the inner variable to something distinct
Use more descriptive variable names to avoid collisions
Access the outer variable through a different reference if needed
How to prevent
Use descriptive, unique variable names
Avoid reusing loop counter names (i, j) in nested functions
Related Resources
Related Lessons
- Scope and Visibility
Learn about scope and shadowing.