0
What are shadowed variables and how can they cause bugs?
kallyani
medium
0completed
14
Answer
A shadowed variable happens when a variable declared inside a function or block has the same name as a variable in an outer scope.
The inner variable “shadows” (hides) the outer one within its scope — meaning the outer variable becomes temporarily inaccessible.
let name = "abc";
function showName() {
let name = "xyz"; // shadows the outer 'name'
console.log(name); // Output: xyz
}
showName();
console.log(name); // Output: abcHere, the inner name variable hides the outer name inside the function.
Why it can cause bugs:
- It can confuse developers who think they’re using the outer variable.
- It may cause unexpected behavior if the inner variable overwrites or hides important data.
In short: Shadowed variables occur when inner variables have the same name as outer ones, often leading to confusing or buggy code. It’s best to use clear, unique names to avoid them.
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0