Skip to content

Commit

Permalink
Learned about Lexical Scoping and Scope chain
Browse files Browse the repository at this point in the history
  • Loading branch information
sohail019 committed Jul 31, 2024
1 parent ce4a683 commit 4f6ba03
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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.
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.

0 comments on commit 4f6ba03

Please sign in to comment.