Programming Fundamentals › Programming Basics
Shadowing
An inner variable hiding an outer one with the same name.
Also known as: variable shadowing, name shadowing
Shadowing is when a variable in an inner scope has the same name as one in an outer scope, so the inner one hides the outer one.
let count = 10;
function demo() {
let count = 1; // shadows the outer count
count += 1;
return count; // 2
}
demo();
console.log(count); // still 10
Inside demo, the name count refers to the local one. The outer one is untouched, but you can’t reach it from there.
Why it causes bugs
- You think you’re updating the outer variable, but you created a new one.
total = 0
def add(x):
total = total + x # UnboundLocalError: assignment makes 'total' local
- In a loop or callback, a reused name like
ioritemhides the outer one, and the wrong value gets used. - Built-in names get hidden:
list = [1, 2]orid = 5meanslist(...)andid(...)stop working in that scope.
Avoiding it
- Use distinct names, especially for outer variables that matter (
total_price, notx). - Don’t reuse built-in names (
list,str,type,max). - Keep functions small, so there’s little room for confusion.
- Turn on linter rules that warn about shadowing.
Shadowing is sometimes deliberate, such as a parameter named like a global it replaces. Be careful that it’s intentional. See scope and global variables.