Advertisement
Both shadowing and illegal shadowing refer to how variable names can "hide" or override others within nested scopes.
Shadowing occurs when a variable declared within a certain scope (like a function or block) has the same name as a variable declared in an outer scope. The inner variable shadows the outer one — meaning, the inner variable takes precedence in its own scope.
Let's take an example where the inner a inside func() shadows the outer variable a.
1let a = 10;
2
3function func() {
4 let a = 20; // Shadows the outer 'a'
5 console.log(a); // 20
6}
7
8func();
9
10console.log(a); // 10Illegal shadowing in JavaScript refers to a syntax error that happens when you try to declare a block-scoped variable (let or const) with the same name as a variable declared using var in the same or an overlapping scope.
For example, if you declare both block-scoped variable and function scoped variable using the same name inside a function causes an illegal shadowing.
1function test() {
2 var a = 10;
3 let a = 20; // SyntaxError: Identifier 'a' has already been declared
4 }As an another example, if you declare a variable with let or const in an outer scope, and then try to redeclare it with var inside a nested block, JavaScript throws an error — even though var is supposed to be function-scoped. Since the var appears in a block, it ends up trying to overwrite the let in the outer scope, which causes a conflict.
1let a = 10;
2 {
3 var a = 20; // SyntaxError: Identifier 'a' has already been declared
4 console.log(a);
5 }Advertisement
JavaScript Coding Exercise 47
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement