When learning JavaScript, you may come across confusing cases where a variable declared inside a block or function seems to “hide” another variable with the same name from an outer scope. This phenomenon is known as Variable Shadowing.
In this article, we’ll explore what variable shadowing is, why it happens, and how to avoid potential bugs caused by it with clear examples and explanations.
What is Variable Shadowing?
Variable shadowing in JavaScript is a phenomenon where a variable declared in an inner scope (such as inside a function or a code block defined by {}) has the same name as a variable in an outer scope.
The inner variable effectively "shadows" or hides the outer variable within the boundaries of its scope. It means, while inside the inner scope, you can only access the inner variable, not the outer one.
Here is a breakdown of the key characteristics:
- Scope Priority: When JavaScript tries to resolve the variable name inside the inner scope, it finds the local declaration first and uses it.
- Isolation: The two variables (inner and outer) are distinct and separate. Modifying the shadowed (inner) variable does not affect the value of the outer variable.
- Mechanism: Shadowing relies on using a variable declaration keyword (var, let, or const) in the inner scope to create a new, local variable with the conflicting name.
let theme = "light"; // Outer variable function changeTheme() { let theme = "dark"; // Inner variable (shadows the outer 'theme') console.log("Inside function:", theme); // Output: dark } changeTheme(); console.log("Outside function:", theme); // Output: light // The outer 'theme' was never changed; it was only hidden inside the function.
Types of Variable Shadowing in JavaScript.
let x = 10; function demo() { let x = 20; // ✅ Legal shadowing console.log(x); // 20 } demo(); console.log(x); // 10
let y = 10; function test() { var y = 20; // ❌ Illegal shadowing console.log(y); } test();
- The outer y is block-scoped (declared with let).
- The inner y (declared with var) belongs to the same function scope.
- JavaScript doesn’t allow this kind of redeclaration; hence, an error occurs.
Shadowing vs Hiding.
- Shadowing: When a local variable (in an inner scope) has the same name as a variable in an outer scope, it makes the outer one inaccessible in that scope. You can’t access the outer variable directly when shadowed.
- Hiding: When a member of a subclass (like a method or variable) has the same name as one in its superclass, it hides the inherited member. You can still access the hidden member using super or the base class name.



Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.