-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Learned about Lexical Scoping and Scope chain
- Loading branch information
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
03 - Chai aur Javascript/16 - Lexical Scoping and Closures/02_lexical_scoping.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
const globalVar = "I am Global" | ||
|
||
function outer(){ | ||
const outerVar = "I am Outer" | ||
|
||
|
||
function inner(){ | ||
const innerVar = "I am Inner" | ||
|
||
console.log(globalVar); // I am Global | ||
console.log(outerVar); // I am Outer | ||
console.log(innerVar); // I am Inner | ||
} | ||
|
||
inner() | ||
} | ||
|
||
outer() | ||
|
||
// In this eg, inner function can access globalVar and outerVar because they are within it's lexical scope. | ||
// Inner function inherit the scope of the parent function where they are defined. |
22 changes: 22 additions & 0 deletions
22
03 - Chai aur Javascript/16 - Lexical Scoping and Closures/03_scope_chain.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
// Scope Chain | ||
|
||
function firstFunction(){ | ||
const firstVar = "I am First" | ||
|
||
function secondFunction(){ | ||
const secondVar = "I am Second" | ||
|
||
function thirdFunction(){ | ||
const thirdVar = "I am Third" | ||
|
||
console.log(firstVar); // I am first | ||
console.log(secondVar); // I am Second | ||
console.log(thirdVar); // I am Third | ||
} | ||
thirdFunction() | ||
} | ||
secondFunction() | ||
} | ||
firstFunction() | ||
|
||
// In this example, thirdFunction can access firstVar and secondVar through the scope chain because of lexical scoping. |