Skip to content

Commit 76d10a2

Browse files
committed
Add shadowing and illegal shadowing question
1 parent 77b7848 commit 76d10a2

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

README.md

+44
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,8 @@
519519
| 469 | [What is globalThis, and what is the importance of it?](#what-is-globalthis-and-what-is-the-importance-of-it) |
520520
| 470 | [What are the array mutation methods?](#what-are-the-array-mutation-methods) |
521521
| 471 | [What is module scope in JavaScript?](#what-is-module-scope-in-javascript) |
522+
| 472 | [What are shadowing and illegal shadowing?](#what-are-shadowing-and-illegal-shadowing) |
523+
522524
<!-- TOC_END -->
523525

524526
<!-- QUESTIONS_START -->
@@ -9104,6 +9106,48 @@ Common use cases and benefits:
91049106
91059107
**[⬆ Back to Top](#table-of-contents)**
91069108
9109+
472. ### What are shadowing and illegal shadowing?
9110+
9111+
Both **shadowing** and **illegal shadowing** refer to how variable names can "hide" or override others within nested scopes.
9112+
9113+
**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.
9114+
9115+
Let's take an example where the inner `a` inside `func()` shadows the outer variable `a`.
9116+
9117+
```javascript
9118+
let a = 10;
9119+
9120+
function func() {
9121+
let a = 20; // Shadows the outer 'a'
9122+
console.log(a); // 20
9123+
}
9124+
9125+
func();
9126+
console.log(a); // 10
9127+
```
9128+
9129+
**Illegal 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.
9130+
9131+
For example, if you declare both block-scoped variable and function scoped variable using the same name inside a function causes an illegal shadowing.
9132+
9133+
```javascript
9134+
function test() {
9135+
var a = 10;
9136+
let a = 20; // SyntaxError: Identifier 'a' has already been declared
9137+
}
9138+
```
9139+
9140+
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.
9141+
9142+
```javascript
9143+
let a = 10;
9144+
{
9145+
var a = 20; // SyntaxError: Identifier 'a' has already been declared
9146+
console.log(a);
9147+
}
9148+
```
9149+
**[⬆ Back to Top](#table-of-contents)**
9150+
91079151
<!-- QUESTIONS_END -->
91089152
91099153
### Coding Exercise

0 commit comments

Comments
 (0)