Shadowing in JavaScript (with var, let, const Examples)
Shadowing in JavaScript is an important concept because it helps us understand why variables can behave differently in certain situations.
By understanding shadowing, we can write cleaner, modular code and avoid unexpected bugs.
Variable Shadowing with let
Shadowing occurs when a variable declared in an inner scope has the same name as a variable in the outer scope.
function test() {
let a = "Hello";
if (true) {
let a = "Hi"; // shadows outer 'a'
console.log(a); // Hi
}
console.log(a); // Hello
}
test();
Explanation
The inner
ashadows the outeraBoth variables exist in different scopes
This is valid shadowing
Illegal Shadowing in JavaScript
Illegal shadowing happens when a variable declared with var tries to shadow a let or const variable from an outer scope.
Rules to remember
letcan be shadowed byletvarcan be shadowed byletletcannot be shadowed byvar
Example: Legal and Illegal Shadowing
function func() {
var a = "Hello";
let b = "Namaste";
if (true) {
let a = "Hi"; // Legal shadowing
var b = "Bye"; // Illegal shadowing
console.log(a);
console.log(b);
}
}
func();
Why is this illegal?
var bis function scopedIt tries to redeclare
bwhich is already declared withletin the same function scopeJavaScript throws a SyntaxError

