Skip to content

Commit 8440f2f

Browse files
committed
feat(Shadowing): Shadowing in JavaScript
Signed-off-by: cankush625 <cankush625@gmail.com>
1 parent 8333110 commit 8440f2f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Advance/shadowing.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Shadowing - If the variable is defined outside the block with the
2+
// same name then the variable inside the block shadows the variable outside the block.
3+
4+
// Shadowing in Block Scope
5+
// This is the valid shadowing
6+
var num = 10;
7+
let digit = 5;
8+
// Block Scope
9+
{
10+
var num = 20;
11+
let digit = 7;
12+
console.log(num); // 20
13+
console.log(digit); // 7
14+
}
15+
console.log(num); // 20
16+
console.log(digit); // 5
17+
18+
// Shadowing in Function Scope
19+
var username = "ankush";
20+
let rank = 1;
21+
function myName() {
22+
var username = "roshan";
23+
let rank = 2;
24+
console.log(username); // roshan
25+
console.log(rank); // 2
26+
}
27+
myName();
28+
console.log(username); // ankush
29+
console.log(rank); // 1
30+
31+
// Illegal Shadowing
32+
// let a = 20;
33+
// {
34+
// var a = 40;
35+
// }
36+
37+
// Legal Shadowing
38+
// let a = 20;
39+
// function sum() {
40+
// var a = 40;
41+
// }
42+
43+
// let a = 20;
44+
// {
45+
// let a = 40;
46+
// }
47+
48+
// var a = 20;
49+
// {
50+
// let a = 40;
51+
// }

0 commit comments

Comments
 (0)